Ajax Principle and Packaging Explanation

Keywords: Javascript JSON JQuery PHP

Everyone uses Ajax every day. The jquery library encapsulates Ajax perfectly and very well. Let's take a look at its internal principle and manually encapsulate its own Ajax library.

For more information on ajax packaging and data processing, see Shanghai Shangxue School< Ajax encapsulated by replace+Jq in Ajax>,<ajax+json data processing>

I. principle

The delivery of native Ajax requires four steps:
1) Create Ajax objects: XMLHttpRequest
2) Set request parameters: open (request parameters [get/post],url address, asynchronous [true/false])
3) Setting the callback function: onreadystateChange is used to process the returned data
4) Send request: send()

//TODO step1: Establish ajax object
var xhr = new XMLHttpRequest();
 //TODO step2: Setting Request Parameters
xhr.open('get','01.php',true);
 //TODO step3: Set callback
xhr.onreadystatechange = function () {
     //Receive returned data
    console.log(xhr.responseText);//responseText Text for receiving background responses
}
 //TODO step4: Send request
xhr.send();

Two, encapsulation

The core idea of encapsulation is to take the dynamic part as a parameter and leave the invariant part there. In the above code, the parameters of request mode (get, post), request address url, request parameter data, successful callback success, failed callback error, etc., are all dynamic changes; while creating Ajax object XMLHttprequest, event monitoring onreadystatechange, etc. Fixed, so the first step is to determine the package parameters:

I. packaging

The core idea of encapsulation is to take the dynamic part as a parameter and leave the invariant part there. In the above code, the parameters of request mode (get, post), request address url, request parameter data, successful callback success, failed callback error, etc., are all dynamic changes; while creating Ajax object XMLHttprequest, event monitoring onreadystatechange, etc. Fixed, so the first step is to determine the package parameters:

# url. Request address

# Data requests data

# Type request type

# Successful callback

# Eror failed callback

# Call return false before beforeSend sends to block sending

# Compleajax requests successful callbacks, which are executed whenever possible

 

function ajax(option){
    //User configuration option Default configuration init
    var init = {
        type:'get',
        async:true,
        url:'',
        success: function () { },
        error: function () { },
        data:{},
        beforeSend: function () {
            console.log('Before sending...');
            return false;
        }
    };
    //TODO step1: Merging parameters
    for(k in option){
        init[k] = option[k];
    }
    //TODO step2: Parameter transformation
    var params = '';
    for(k in init.data){
        params += '&'+k+'='+init.data[k];
    }
    var xhr = new XMLHttpRequest();
    // type url
    //TODO step3: Distinguish get and post,Dissemination of information
    var url = init.url+'?__='+new Date().getTime();
    //TODO step4: Before sending
    var flag = init.beforeSend();
    if(!flag){
        return;
    }
    if(init.type.toLowerCase() == 'get'){
        url += params;
        xhr.open(init.type,url,init.async);
        xhr.send();
    }else{
        xhr.open(init.type,url,init.async);
      xhr.setRequestHeader('content-type','application/x-www-form-urlencoded');
        xhr.send(params.substr(1));
    }
    xhr.onreadystatechange = function () {
        if(xhr.readyState == 4){
            if(xhr.status == 200){
                init.success(xhr.responseText);
            }else{
                //error
                init.error();
            }
        }
    }
}

 

Here we need to note that get and post have different location of parameters. The get request needs to be stitched directly behind the url address. The post request needs to be passed in the send method, and this is the request header setRequestHeader('content-type','application/x-www).-

form-urlencoded'), so when encapsulating, make a distinction.

Because of too many parameters, users do not need to pass in many parameters every time, otherwise it will be very cumbersome to use. So we take the form of default parameters, users do not pass in is using the default values, the incoming is using user parameters.

Use examples

ajax({
    url: 'test.json',
    data:{test:123,age:456},
    //type:'post',
    success: function (res) {
        console.log(res);
    }
});

Posted by irishdreaming on Sun, 19 May 2019 19:09:42 -0700