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

Now that you’ve learned about AJAX, let’s wrap GET requests

Ajax GET request encapsulation

function ajax(url,obj,success,error){
    // 0. Convert the object to a string
    var str = objToString(obj); // Obj is used to separate the URL from the data to be passed. It can be treated as an object. In the process of passing, obj is converted into the corresponding string to be concatenated at the end of the URL. So the data goes in. T = new Date().getTime();
    // 1. Create an asynchronous object XMLHTTP;
    var xmlhttp; 
    if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari 
      xmlhttp=new XMLHttpRequest(); 
    } else{// code for IE6, IE5 
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
    }
    // 2. Set the request mode and address.
        //xmlhttp.open("GET",url,true);
        xmlhttp.open("GET",url+"? t=" +str;	
    // 3.
            xmlhttp.send();
    // 4.
    xmlhttp.onreadystatechange = function(){
        if (xmlhttp.readyState === 4) {
            if (xmlhttp.status >= 200 && xmlhttp.status < 300 || xmlhttp.status == 304) {
                // 5. Process the returned result;
                success(xmlhttp);// Callback after success;
            }else{
                error(xmlhttp);// Callback after failure;}}}}function objToString(obj){
  obj.t = new Date().getTime();
  var res =[];
  for(var key in obj){
    res.push(key + "=" +obj.[key]);
  }
  return res.join("&");
}
Copy the code

Pay attention to

  1. Compatibility problems in Internet Explorer
  2. When we pass the URL we need to pass the data that we added, but that doesn’t write very well, so we can pass a parameter obj, and that obj is just to separate the URL from the data that we’re passing, we can think of it as an object, and as we pass it, we’re going to concatenate obj into the corresponding string at the end of the URL. So the data goes in. T = new Date().getTime();

Other issues

There are two more details that need to be addressed in the ajax methods we currently encapsulate:

  1. When we use our ajax put send a request to the remote server, we need to wait for the remote server to respond to our request, waiting for the remote server will be the result of the response is returned to us, but the response speed is uncertain, because the speed of response is by the local network joint decision and the speed of the remote server, So we can’t wait for the server to respond. So here we need to add another function: the function to set the timeout time, that is, to tell it how long my request will wait, if there is no response within such a long time, I will automatically terminate this request here;
function ajax(url,obj,timeout,success,error){
    // 0. Convert the object to a string
    var str = objToString(obj); 
    // 1. Create an asynchronous object XMLHTTP;
    var xmlhttp,timer; 
    if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari 
      xmlhttp=new XMLHttpRequest(); 
    } else{// code for IE6, IE5 
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
    }
    // 2. Set the request mode and address.
        //xmlhttp.open("GET",url,true);
        xmlhttp.open("GET",url+"? t=" +str;  
    // 3.
        xmlhttp.send();
    // 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;
                success(xmlhttp);// Callback after success;
            }else{
                error(xmlhttp);// Callback after failure;}}}}function objToString(obj){
      obj.t = new Date().getTime();
      var res =[];
      for(var key in obj){
        res.push(key + "=" +obj.[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
  1. There is another problem with the above situation, when we send a request, we cannot have Chinese in the URL.

When we search for keywords on Baidu, such as Zhang SAN, we usually see the address bar: https://www.baidu.com/s?wd= Zhang SAN; But if we copy it to the editor, it will look something like https://www.baidu.com/s?wd=%E5%BC%AO%E4%B8%90. In fact, when it submits the request, it is not the Chinese character zhang SAN, but the character %E5%BC%AO%E4%B8%90. The Chinese character “Zhang SAN” is displayed to you by the browser. What is actually submitted is the string “%E5%BC%AO%E4%B8%90”.

So we need to pass the Chinese processing to the server in the special processing obj function.

You need to convert the key and value to a non-Chinese form because urls cannot have Chinese. Transcoding using encodeURIComponent(); Only alphanumeric underscores and ASCII characters can appear in urls

Improvements are as follows:

function ajax(url,obj,timeout,success,error){
    // 0. Convert the object to a string
    var str = objToString(obj); 
    // 1. Create an asynchronous object XMLHTTP;
    var xmlhttp,timer; 
    if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari 
      xmlhttp=new XMLHttpRequest(); 
    } else{// code for IE6, IE5 
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
    }
    // 2. Set the request mode and address.
        //xmlhttp.open("GET",url,true);
        xmlhttp.open("GET",url+"? t=" +str;  
    // 3.
        xmlhttp.send();
    // 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;
                success(xmlhttp);// Callback after success;
            }else{
                error(xmlhttp);// Callback after failure;}}}}function objToString(obj){
      obj.t = new Date().getTime();
      var res =[];
      for(var key in obj){
            // We need to convert the key and value to a non-Chinese form, because the URL cannot have Chinese. Transcoding using encodeURIComponent(); Only alphanumeric underscores and ASCII characters can appear in urls
        res.push(encodeURIConponent(key) + "=" +encodeURIConponent(obj.[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