ajax同步和非同步差異, 先看2段代碼:
代碼一:
複製代碼 代碼如下: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同步
conn.send(param);
var strReturn = conn.responseText;
alert("1");
if (strReturn != "") {
return Ext.decode(conn.responseText);
} else {
return null;
}
alert("2");
};
代碼二:
Ajax 同步請求方式: 複製代碼 代碼如下: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非同步
conn.send(param);
var strReturn = conn.responseText;
alert("1");
if (strReturn != "") {
return Ext.decode(conn.responseText);
} else {
return null;
}
alert("2");
};
同步和非同步差異如下:
conn.open('POST',Url,true); // ajax非同步
conn.open('POST',Url,false); // ajax同步
對於代碼二,為非同步ajax請求,執行結果為:先執行alert(2)再執行alert(1), 非同步意思就是說一旦conn.open請求一發出,前端不去等待它的響應便執行後面的代碼,所以alert(2)先執行了,然後當響應response到達以後才執行alert(1);
對於代碼一,為同步的ajax請求,執行結果為:先執行alert(1)再執行alert(2), 同步的意思就是說一旦conn.open請求一發出,前端就去等待它的響應,響應完成以後,alert(1)先執行了,然後alert(2);