Native js realizes encapsulation of Ajax of imitates jquery

  • 2021-07-13 04:11:52
  • OfStack

Preface

As we all know, jquery is used very frequently in our daily development. Compared with js, we save lengthy code for obtaining elements, and don't need to consider some troublesome compatibility problems. More convenient animation implementation and more convenient method call make us feel that jquery is really more comfortable. However, jquery is still a package of js in the final analysis. We should not only use it comfortably, but also deeply understand its principle, so as to better use it.

First of all, in order to realize that the encapsulated function can pass in an infinite number of parameters, when using the function we are about to encapsulate, we need to use objects to pass parameters, in the following form:


//data Pass it as a parameter to our encapsulated function below 
var data = {
       // Data 
       user:"yonghu1",
       pass:'12345',
       age:18,
       // Callback function 
       success:function (data){
        alert(data);
       }
      }

Function encapsulation:

1. Encapsulate an auxiliary function and splice the incoming objects into url strings


function toData(obj){
  if (obj == null){
    return obj;
  }
  var arr = [];
  for (var i in obj){
    var str = i+"="+obj[i];
    arr.push(str);
  }
  return arr.join("&");
}

2. Package Ajax


function ajax(obj){
  // Specify the default value of the submission method 
  obj.type = obj.type || "get";
  // Set whether it is asynchronous, and the default is true( Asynchronous )
  obj.async = obj.async || true;
  // Set the default value of data 
  obj.data = obj.data || null;
  if (window.XMLHttpRequest){
    // Non ie
    var ajax = new XMLHttpRequest();
  }else{
    //ie
    var ajax = new ActiveXObject("Microsoft.XMLHTTP");
  }
  // Differentiate get And post
  if (obj.type == "post"){
    ajax.open(obj.type,obj.url,obj.async);
    ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    var data = toData(obj.data);
    ajax.send(data);
  }else{
    //get test.php?xx=xx&aa=xx
    var url = obj.url+"?"+toData(obj.data);
    ajax.open(obj.type,url,obj.async);
    ajax.send();
  }

  ajax.onreadystatechange = function (){
    if (ajax.readyState == 4){
        if (ajax.status>=200&&ajax.status<300 || ajax.status==304){
          if (obj.success){
            obj.success(ajax.responseText);
          }
        }else{
          if (obj.error){
            obj.error(ajax.status);
          }
        }
      }
   }  
}


Related articles: