This article has participated in the Denver Nuggets Creators Camp 3 “More Productive writing” track, see details: Digg project | creators Camp 3 ongoing, “write” personal impact

preface

As explored in the previous two articles today, we’ve wrapped AJAX, but we still have a lot of problems with it compared to what others have wrapped. Let’s take a look

The problem

The jQuery method is as follows

$.ajax({
   type: "post".url: "some.php".data: "name=John&location=Boston".success: function(msg){
     alert( "Data Saved: "+ msg ); }});Copy the code

When I use my own wrapped code, I feel a little different from jQuery’s official Ajax, so I further improve

First, pass the case of the request type, which officially succeeds

Second, we are passing many arguments, and the order of the arguments must be consistent. What is officially passed is an object, and the values in the object are not in order

Third, we wear data with the name obj, the official use is data, semantics more appropriate

The solution

To solve the first problem use toLowerCase() or toUpperCase() to convert the type toUpperCase or lowercase for comparison, as in:

option.type.toLowerCase() === 'get'
Copy the code

Solve the second problem by replacing the passed parameter with an object; The argument used in the previous section passed: object name. Gets the form of the property name.

/ / type, url, obj, timeout, success, and the error to replace all the parameters with an object
function ajax(option){....}
Copy the code

Solve the third problem, is the data name data can be

That’s pretty much it. I’ll finish it at the end

Improve the code

function ajax(option){/ / type, url, obj, timeout, success, and the error to replace all the parameters with an object {}
    // 0. Convert the object to a string
    var str = objToString(option.data); 

    // 1. Create an asynchronous object XMLHTTP;
    var xmlhttp,timer; 
    if (window.XMLHttpRequest){
      xmlhttp=new XMLHttpRequest(); 
    } else{// code for IE6, IE5 
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
    }

    // 2. Set the request mode and address.
    // Determine whether the request type is POST or GET
    if (option.type.toLowerCase() === 'get') {
        xmlhttp.open(option.type,option.url+"? t=" +str,true);
    // 3.
        xmlhttp.send();
    }else{
            xmlhttp.open(option.type,option.url,true);
            SetRequestHeader (header,value); setRequestHeader(header,value);
            xmlhttp.setRequestHeader("Content-type"."application/x-www-form-urlencoded"); 
        // 3.
            xmlhttp.send(str);

    }   

    // 4.
    xmlhttp.onreadystatechange = function(){
        clearInterval(timer);
        if (xmlhttp.readyState === 4) {
            if (xmlhttp.status >= 200 && xmlhttp.status < 300 || xmlhttp.status == 304) {
                // 5. Process the returned result;
                option.success(xmlhttp);// Callback after success;
            }else{
               option. error(xmlhttp);// Callback after failure;}}}}/ / processing obj
function objToString(data){
  data.t = new Date().getTime();
  var res =[];
  for(var key in data){
    // We need to convert the key and value to a non-Chinese form, because the URL cannot have Chinese. Use encodeURIComponent ();
    res.push(encodeURIConponent(key) + "=" +encodeURIConponent(data.[key]));
  }
  return res.join("&");
}

// Determine whether the timeout is passed in
if(timeout){
    timer = setInterval(function(){
        xmlhttp.abort();// Interrupt the request
        clearInterval(timer);
    },timeout);
}
Copy the code

END

That’s all for this article

If you have any questions, please leave a comment