寫 jQuery 一段時間後會發現,只要用 Ajax 載入資料,就幾乎一定要考慮程式碼的執行順序。最近某個專案就用到了 Ajax 同步。
同步:JS 執行到這個 Ajax 時,會把後續所有程式碼暫停,頁面進入類似假死狀態,直到請求回來才繼續往下跑。
非同步:Ajax 還在飛行途中,後面的程式碼照樣執行,互不阻塞。
對應的屬性是 async,預設 true(非同步),設為 false 即為同步。
$.ajax({
type: "post",
url: "path",
cache: false,
async: false,
dataType: ($.browser.msie) ? "text" : "xml",
success: function(xmlobj){ }
});
這個屬性確實能解決程式碼順序的困擾,但若到處濫用,頁面就會一次次假死,反而把體驗弄壞。
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. 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.
async 為預設的 true 時,ajax 送出請求後,在等待伺服器回應的這段時間裡,前台會繼續執行 ajax 區塊之後的腳本,直到回應抵達才去跑 success。也就是說,同一時間有兩條線在跑:
$.ajax({
type: "POST",
url: "Venue.aspx?act=init",
dataType: "html",
success: function(result){
// function1
f1();
f2();
},
failure: function (result) {
alert('Failed');
}
});
function2();
上例中,ajax 送出請求後會停在 f1() 等回應,但同時(就在這段等待裡)前台已經把 function2() 跑完了。此刻可視為 f1() 與 f2() 兩條線各自推進。
反過來,把 async 設為 false,ajax 就是同步的:請求送出後停在 f1() 這裡,不會去執行 function2(),直到 f1() 這段全部跑完為止。
絕大多數情況應該維持非同步,把「順序」問題用回呼或 Promise 來解決,而不是靠凍結 UI。同步請求除了讓畫面卡住, also 會讓 Loading 動畫、連點防護這些機制全部失效。如果真的遇到必須依序執行的多段請求,用回呼串接、或是以 jQuery 的 Deferred / $.when 來編排,才是長遠之計。