ajax 同步請求和非同步請求的差異分析

來源:互聯網
上載者:User

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);

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.