Summary of Several ajax Request Methods in Practical Business

Keywords: JSON PHP

Recently, we made a function page to measure the speed of a single node. The logic of speed measurement is that when we measure the upload speed, the front-end transmits 5m data to the server, records the time of uploading and returning data, downloads 1m data from the server, records the successful time of downloading and downloading, uploads and downloads ajax synchronization to avoid the problem of client bandwidth blocking, and carries out three times. Take the average. In the development process, because of the problem of ajax synchronization and asynchrony, we have taken many detours, especially to summarize the business logic we met before.

1. Ordinary ajax, async is synchronous asynchronous processing, after success, there will be data return value, status request status, xhr encapsulation is the request header, but it should be noted that not all the request header information can be obtained, such as center-length can not be obtained.

$.ajax({
    type: "GET",  
    async: true,  //Asynchronous execution defaults to true asynchronous
    url: url,  
    dataType: "json",
    // jsonp: "callback",
    success: function(data, status, xhr){
        console.log(data);//Return value
        console.log(status);//state
        console.log(xhr);//obj
        console.log(xhr.getResponseHeader("Content-Type"));//application/octet-stream
        console.log(xhr.getResponseHeader("Center-Length"));//null
    }

});
2. Sometimes the business logic is like this: Request 2 depends on the return result of Request 1, Request 3 depends on the return result of Request 2. If written in the way of callback, it will be very lengthy. There are two ways to solve this problem. First, look at the solution of ES5.

(1)ES5 solution, using ajax synchronization, the default ajax is asynchronous, that is, multiple requests are executed at the same time, after changing to synchronization, ajax is executed one by one, so ajax 2 can get the result of ajax 1 return.

let res1 = ""
let res2 = ""

$.ajax({
    type: 'get', 
    async: false,  //Synchronized execution defaults to true asynchrony
    url: pars.domain + "/api.php?Action=xxx&date=2017-03-08&t=" + (new Date).getTime(),
    dataType: 'json',  
    success: function(res) {  
        if(res.code == 0){  
            res1 = res.data.bandwidth[0]
        }else{  
            
        }  
    }
});

$.ajax({
    type: 'get', 
    async: false,  //Synchronized execution defaults to true asynchrony
    url: pars.domain + "/api.php?Action=xxx&date=2017-03-08&dom1111" + res1 + "&t=" + (new Date).getTime(),
    dataType: 'json',  
    success: function(res) {  
        if(res.code == 0){  
            res2 = res.data.bandwidth[0]
        }else{  
            
        }  
    }
});

(2)ES6 solution, using promise's then method, the effect is the same as above, Ajax will be executed sequentially, and the following Ajax will get the return value of the previous ajax, so that the code will look very smooth to write.

let pro = new Promise(function(resolve,reject){
    let url = pars.domain + "/api.php?Action=xxx=2017-03-08&t=" + (new Date).getTime()
    let ajax = $.get(url, function(res) {
        if (res.code == 0) {
            resolve(resData);
        }
        else{
        }
    }, "json");
    console.log('request pro Success');
});


//Successful handling with the then and exception handling with the catch
pro.then(requestA)
    .then(requestB)
    .then(requestC)
    .catch(requestError);

function requestA(res){
    console.log('The results of the previous step are as follows:'+res);
    console.log('request A Success');
    let proA = new Promise(function(resolve,reject){
        let url = pars.domain + "/api.php?Action=xxx&date=2017-03-08&t=" + (new Date).getTime()
        let ajax = $.get(url, function(res) {
            if (res.code == 0) {
                resolve(resData);
            }
            else{
            }
        }, "json");
    });
    return proA
}

function requestB(res){
    console.log('The results of the previous step are as follows:'+res);
    console.log('request B Success');
    let proB = new Promise(function(resolve,reject){

        let url = pars.domain + "/api.php?Action=xxx&date=2017-03-08&t=" + (new Date).getTime()
        let ajax = $.get(url, function(res) {
            if (res.code == 0) {
                resolve(resData);
            }
            else{
            }
        }, "json");
    });
    return proB
}

function requestC(res){
    console.log('The results of the previous step are as follows:'+res);
    console.log('request C Success');
    let proC = new Promise(function(resolve,reject){
        let url = pars.domain + "/api.php?Action=xxx&date=2017-03-08&t=" + (new Date).getTime()
        let ajax = $.get(url, function(res) {
            if (res.code == 0) {
                resolve(resData);
            }
            else{
            }
        }, "json");
    });
    return proC
}

function requestError(){
    console.log('request was aborted');
}
3.jsonp cross-domain, add script tags dynamically to achieve cross-domain, note that there is a callback that needs to be negotiated with server

function switchEngineRoomAjax(api,statusChanged){
    var api = api;
    var statusChanged = statusChanged;
    var url = api + "?method=setStatus" + "&status=" + statusChanged;

    $.ajax({
        type: "GET",  
        url: url,  
        dataType: "jsonp",
        jsonp: "callback",// The callback here is for the back end to receive. The front end completes the callback by dynamically adding script tags.
        success: function(res){
            if (res.code == 0) {
                console.log('Change state jsonp Successful data acquisition!');
            }
            else{
            }
        }
    });
};
4. We will also encounter this business logic, ajax1 Ajax 2 ajax3 asynchronous requests, which do not necessarily return data first. After the successful request, we will execute a callback function. It should be noted that a separate Ajax also needs to be a new promise.

ajax1:function(){
    var promise = new Promise(function (resolve, reject) {
        var url = "/api.php?Action=xxx;
        $.get(url, function(res) {
            if (res.code == 0) {
                resolve('queryLog Finish!');
            }
            else{
            }
        }, "json");
    });
    return promise
},
ajax2: function(){
    var promise = new Promise(function (resolve, reject) {
        var url = "/api.php?Action=xxx;
        $.get(url, function(res) {
            if (res.code == 0) {
                resolve('queryGroupNodeList Finish!');
            }
            else{
            }
        }, "json");
    });
    return promise
},
ajax3: function(){
    var promise = new Promise(function (resolve, reject) {
        var url = "/api.php?Action=xxx;
        $.get(url, function(res) {
            if (res.code == 0) {
                resolve('queryGroupNodeMapList Finish!');
            }
            else{
            }
        }, "json");
    });
    return promise
},
initQuery: function(){
    var mySelf = this;
    var promiseList = [];
    var ajax1Promise = mySelf.ajax1();
    var ajax2Promise = mySelf.ajax2();
    var ajax3Promise = mySelf.ajax3();

    promiseList.push(ajax1Promise,ajax2Promise,ajax3Promise);
    var p1 = new Promise(function (resolve, reject) {
        console.log('Create 1.2 Second Delay Execution promise');
        setTimeout(function () {
            resolve("1.2 Second Delay Execution promise");
        }, 1200);
    });
    promiseList.push(p1)

    Promise.all(promiseList).then(function (result) {
        console.log('ajax Complete implementation:' + JSON.stringify(result)); // ["Hello", "World"]
        mySelf.assembleTableData();
    });
},



Posted by limey on Sun, 21 Apr 2019 23:09:34 -0700