There are many frameworks that encapsulate Ajax and just call it when you need it, jquery being the most common. Why do we need to learn ajax encapsulation? First, enhance our ajax awareness, and second, if only because Ajax requests require the introduction of a framework, we can wrap one ourselves so that we don’t need to introduce additional frameworks.
First, the attention of packaging
Encapsulation is to realize the common use of the same part, save resources, improve code reuse, and high work efficiency, so it is necessary to pass in different parameter event types through the call, attention should be paid to the following points:
1.1, the refs
When sending an Ajax request, the main parameters are:
- The request url
- Request type
- Request parameters
- Success callback
- Failure callback
- timeout
The above six parameters must be set to be dynamically passed in for easy control of any Ajax request. The timeout period can be set uniformly, and it is more convenient to control the timeout of any request if it is passed as a parameter.
1.2. Request types are handled separately
There are two request types: GET and POST. When the GET type is transmitted, the data follows the URL address. When the POST type is transmitted, the data is carried in the request body. So you need to judge and deal with it separately.
if(type == 'GET'){ xhr.open( 'GET' , url+'? '+strData , true ) shr.send() }else{ xhr.open('POST',url,true) xhr.setRequestHeader('content-type','application/x-www-form-urlencoded') xhr.send( strData ) }Copy the code
1.3. Request timeout processing
When the network service or interface is abnormal, no response is received and the page does not respond. A global timeout process is required. If no response is returned within the specified time, the request is automatically terminated and an exception is returned.
Use the following syntax:
// Set the time to 2s xhr.timeout = 2000; Xhr.ontimeout = function(){console.log(' network exception, try again later ')}Copy the code
1.4. Error handling
If the network is interrupted and a request cannot be sent to the server, handle the request failure. Use onError event handling.
Use the following syntax:
Xhr.onerror = function(){console.log(" network error, please check the network ")}Copy the code
Second, encapsulate ajax code
According to the ajax request process, the encapsulation code is as follows: Easy to use in the future, it is recommended to save.
function ajax(option) { // method, url, data, timeout, success, error var xhr; var str = data2str(option.data); if (window.XMLHttpRequest) { xhr = new XMLHttpRequest(); }else { xhr = new ActiveXObject("Microsoft.XMLHTTP"); } if (option.type.toLowerCase() === 'post') { xhr.open(option.type, option.url, true); xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xhr.send(str); } else if (option.type.toLowerCase() === 'get') { xhr.open(option.type, option.url + '? ' + str, true); xhr.send(); } xhr.onreadystatechange = function () { if (xhr.readyState === 4) { clearTimeout(timer); if (xhr.status >= 200 && xhr.status < 300 || xhr === 304) { option.success(xhr); }else { option.error(xhr); }}}; if (option.timeout) { var timer = setTimeout(function () { xhr.abort(); clearTimeout(timer); Function data2str(data) {var res = []; data.t = new Date().getTime(); for (var key in data) { res.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key])); } return res.join('&'); }Copy the code
When used, the call code is as follows:
Ajax ({method:'GET', url:'1.txt', data:{// request data}, timeout:2000, success (res)=>{console.log(' return with success ',res.response)}, Error: err => {console.log(' error message ',err)}})Copy the code