Home  >  Article  >  Web Front-end  >  Difference analysis between ajax synchronous requests and asynchronous requests_javascript skills

Difference analysis between ajax synchronous requests and asynchronous requests_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:05:151499browse

The difference between ajax synchronization and asynchronous, let’s look at 2 pieces of code first:
Code 1:

Copy the code The code is as follows:

Synchronize = function(url,param) {
function createXhrObject() {
var http;
var activeX = [ "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP" , "Microsoft.XMLHTTP" ];
try {
http = new XMLHttpRequest;
} catch (e) {
for (var i = 0; i < activeX.length; i) {
try {
http = new ActiveXObject(activeX[i]);
break;
} catch (e) {}
}
} finally {
return http;
}
}
var conn = createXhrObject();
conn.open("POST", url, false);//ajax synchronization
conn.send(param);
var strReturn = conn.responseText;
alert("1");
if (strReturn != "") {
return Ext.decode(conn.responseText);
} else {
return null;
}
alert("2");
};

Code 2:
Ajax synchronous request method:
Copy code The code is as follows:

Synchronize = function(url,param) {
function createXhrObject() {
var http;
var activeX = [ "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP" ];
try {
http = new XMLHttpRequest;
} catch (e) {
for (var i = 0; i < activeX.length; i) {
try {
http = new ActiveXObject(activeX[i]);
break;
} catch (e) {}
}
} finally {
return http;
}
}
var conn = createXhrObject();
conn.open( "POST", url, true);//ajax asynchronous
conn.send(param);
var strReturn = conn.responseText;
alert("1");
if (strReturn ! = "") {
return Ext.decode(conn.responseText);
} else {
return null;
}
alert("2");
};

The difference between synchronous and asynchronous is as follows:

conn.open('POST',Url,true); // ajax asynchronous
conn.open('POST',Url ,false); // ajax synchronization

For code two, it is an asynchronous ajax request. The execution result is: first execute alert(2) and then execute alert(1). Asynchronous means that once conn.open As soon as the request is sent, the front end executes the following code without waiting for its response, so alert(2) is executed first, and then alert(1) is executed when the response arrives;

For code one, it is The execution result of a synchronous ajax request is: execute alert(1) first and then alert(2). Synchronization means that once the conn.open request is issued, the front end will wait for its response. After the response is completed, alert(1 ) is executed first, then alert(2);
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn