Detailed explanation of several ajax request methods that may be encountered in actual practice.

Source: Internet
Author: User

Detailed explanation of several ajax request methods that may be encountered in actual practice.

Preface

Recently, I was working on a function page for Speed Measurement for a single node. The logic of speed measurement is that when the upload speed is measured, the frontend transmits 5 MB of data to the server to record the time when data is uploaded and returned, during the download speed test, 1 MB of data is downloaded from the server, recording the download and download success time. ajax synchronization is used for uploading and downloading to avoid bandwidth blocking on the client, and take the average value three times. During the development process, due to the problem of ajax synchronization and Asynchronization, many detours were taken, and the business logic encountered previously was summarized specially.

The ajax request method is as follows:

I. Normal ajax and async are synchronous and asynchronous processing. After success, there will be data return values, status Request status, and xhr encapsulates the request header, but note that yes, not all request header information can be obtained, for example, center-length cannot 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); // status 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 returned result of request 1, and request 3 depends on the returned result of request 2. If it is written in callback mode, it will be very lengthy, there are two solutions. First, let's look at the ES5 solution.

(1) ES5 solution: Use ajax for synchronization. By default, ajax is asynchronous, that is, multiple requests are executed simultaneously. After being synchronized, ajax is executed one by one, in this way, ajax2 can get the returned results of ajax1.

Let res1 = "" let res2 = "" $. ajax ({type: 'get', async: false, // The default value of synchronous execution is true asynchronous 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, // The default value of synchronous execution is true asynchronous 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: Use the then method of promise to achieve the same effect as above. ajax will be executed in order, and the subsequent ajax will get the previous ajax return value, in this way, the code looks smooth.

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 successfully') ;}); // The operation is successfully processed with then, and the catch process exception is pro. then (requestA ). then (requestB ). then (requestC ). catch (requestError); function requestA (res) {console. log ('previous result: '+ res); console. log ('request A successfully'); 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 ('previous result: '+ res); console. log ('request B successfully'); 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 ('previous result: '+ res); console. log ('request C successfully'); 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 failed ');}

Iii. jsonp cross-origin: dynamically Add the script tag to implement cross-origin. Note that there is a callback that needs to be negotiated with the 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 used for receiving at the backend, the frontend dynamically adds the script tag to complete the callback success: function (res) {if (res. code = 0) {console. log ('the status of jsonp has been changed! ') ;}Else {}}});};

4. This kind of business logic will also run into. ajax1 ajax2 ajax3 three asynchronous requests may not necessarily return data first. After all the requests are successful, a callback function is executed. Note that, the separate ajax must also be the 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 finished! ') ;}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 completed! ') ;}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 finished! ') ;}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 seconds delayed execution promise '); setTimeout (function () {resolve ("1.2 seconds delayed execution promise") ;}, 1200) ;}); promiseList. push (p1) Promise. all (promiseList ). then (function (result) {console. log ('ajax is all executed: '+ JSON. stringify (result); // ["Hello", "World"] mySelf. assembleTableData ();});},

Summary

The above is all the content of this article. I hope the content of this article will help you in your study or work. If you have any questions, please leave a message, thank you for your support.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.