First, encapsulate the native xhr as an ajax class
xhr and usage see previous articles
1. Determine the request header and other information according to the url.
var _headerConfig = {}; if(url.indexOf('getcaptcha') !== -1) { _headerConfig = { Accept: 'image/png', responseType: 'arraybuffer', } } else if(url.indexOf('files/upload') !== -1) { _headerConfig = { 'Content-Type': 'multipart/form-data', responseType: 'json', } } else { _headerConfig = { 'Content-Type': 'application/json', Accept: 'application/json', responseType: 'json', } }
2. Determine the request method and parameters according to the information in the parameter information
if("method" in options) { options.method = options.method.toUpperCase(); } else { options.method = "GET"; } if(options.method !== "GET") { if(!(options.params instanceof FormData)) { options.params = JSON.stringify(options.params); } }
3. Open xhr and send according to the head and other information settings
this.xhr.open(options.method, url, true); for(var _i in _headerConfig) { if(_i === 'responseType') { this.xhr.responseType = _headerConfig[_i]; } else { this.xhr.setRequestHeader(_i, _headerConfig[_i]); } } if(token) { this.xhr.setRequestHeader("token", token); } this.xhr.send(options.params);
4. Implement chain programming: return this at the end of each function;
5. Execute callback after implementation
This problem has been combined with chain programming for a long time.
ajax.prototype.complete = function(completeFunction) { this.xhr.onreadystatechange = function(e) { if(this.readyState === 4) { completeFunction(this); } } return this; }
2. request class of encapsulation practicability
In a project, it is often necessary to encapsulate the request and use the ajax class to initiate the request. The address function of the splice request.
1. Create a splicing method.
var requstUrl = { baseURL: URL, API: { NEWS: '/news', LOGIN: '/', }, // API is a parameter in API, used to splice url // method is the address after the API, which is used to splice the last part of the url. // params parameters required for get request createUrl: function(api, method, params) { var _requestUrl = this.baseURL + this.API[api] + method; if(params) { for(var i of params) { _requestUrl += (_requestUrl.indexOf("?") == -1 ? "?" : "&"); _requestUrl += name + "=" + value; } } return _requestUrl; } }
2. Determine each request.
function handleRequest() { } // get request has parameters. handleRequest.prototype.getDataUseGet = function(api, method, params) { var _url; var ajax = new Ajax(); var token = sessionStorage.getItem('token'); if(params) { _url = requstUrl.createUrl(api, method, params); } else { _url = requstUrl.createUrl(api, method); } return ajax.request(_url, { method: 'GET', params: params }, token); } // get request without token handleRequest.prototype.getDataUseGetWithoutToken = function(api, method, params) { var _url; var ajax = new Ajax(); if(params) { _url = requstUrl.createUrl(api, method, params); } else { _url = requstUrl.createUrl(api, method); } return ajax.request(_url, { method: 'GET', params: params }); } // post request with token handleRequest.prototype.getDataUsePost = function(api, method, params) { var _url = requstUrl.createUrl(api, method); var token = sessionStorage.getItem('token'); var ajax = new Ajax(); console.log(createAjaxObj(_url, { method: 'POST', params: params }, token)); return ajax.request(_url, { method: 'POST', params: params }, token); } // post request without token handleRequest.prototype.getDataUsePostWithOutToken = function(api, method, params) { var _url = requstUrl.createUrl(api, method); var ajax = new Ajax(); return ajax.request(_url, { method: 'POST', params: params }); } // put request with token handleRequest.prototype.getDataUsePut = function(api, method, params) { var _url = requstUrl.createUrl(api, method); var token = sessionStorage.getItem('token'); var ajax = new Ajax(); return ajax.request(_url, { method: 'PUT', params: params }, token); } // put request without token handleRequest.prototype.getDataUsePutWithOutToken = function(api, method, params) { var _url = requstUrl.createUrl(api, method); var ajax = new Ajax(); return ajax.request(_url, { method: 'PUT', params: params }); } // delete request with token handleRequest.prototype.deleteData = function(api, method, params) { var _url = requstUrl.createUrl(api, method); var token = sessionStorage.getItem('token'); var ajax = new Ajax(); return ajax.request(_url, { method: 'DELETE', params: params }, token); }
This method feels like it can be encapsulated again.
Three, use
1. Use code
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body> </body> <script src="ip.js" type="text/javascript"></script> <script src="xhr.js" type="text/javascript"></script> <script src="request.js" type="text/javascript"></script> <script type="text/javascript"> var data = { "captcha": "string", "password": "string", "username": "string" }; var test = new handleRequest(); test.getDataUsePostWithOutToken('LOGIN', 'login',data).complete(function(result) { console.log(result) }) </script> </html>
2, result
Request initiated successfully.
Complete code Click to view
Above.