標籤:des http io os ar for strong sp 資料
今天來大概說說AJAX中的同步與非同步。其實,就我的理解,同步與非同步區別就是程式執行過程中是否有等待。
同步:意思就是js代碼載入到當前的 AJAX時候,會等待AJAX代碼執行完畢後再開始載入其他代碼;
非同步:js代碼是指當載入到 AJAX時候,在AJAX代碼執行的同時 ,也會執行其他代碼。
jquery 的async 屬性:預設 情況下 ,為true :非同步, 標註為false:表示同步
官方解釋:
async
Boolean
Default: true
By default, all requests are sent asynchronous (e.g. this is set to true by default). If you need synchronous requests, set this option to false. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active.
翻譯如下:非同步處理方式:傳回型別為boolean型,
預設情況下所以請求為非同步方式處理,傳回值是true;如果需要同步的要求,可以傳回值設定為false,但是請注意:在同步請求的時候,可能會暫時鎖定瀏覽器,其他任何行為均被禁止,而同步請求行為是活動的。
success
Function
A function to be called if the request succeeds. The function gets passed two arguments: The data returned from the server, formatted according to the ‘dataType‘ parameter, and a string describing the status. This is an Ajax Event.
翻譯如下:當函數請請求返回成功時,將會得到2個參數,1.從伺服器端返回的資料。2.根據資料類型參數的格式化和描述狀態的字串,這個被成為 一個ajax事件。
非同步:當ajax發送請求後,在等待 server端返回的過程中,前台會繼續執行ajax後面的代碼,直到server端返回正確的結果,才會執行success,即無等待過程,執行的時候分為2個線程。
看下如下的代碼:
$.ajax({
type:"POST",
url:"Venue.aspx?act=init",
dataType:"html",
success:function(result){ //function1()
f1();
f2();
}
failure:function (result) {
alert(‘Failed‘);
}
}
function2();
前面我們已經說到,預設情況下async預設為true, 非同步處理方式,就是說當ajax發送請求後,將停留在function1(),在等待伺服器返回結果,但在等待過程中 ,前台會繼續執行function2(),此時就出現了 2個線程。
同步 處理方式:當把async設為false,在ajax發出請求後,會等待function1(),並不會執行function2(),直到function1()的部分執行完畢為止 。
AJAX同步與非同步