jQuery 1.5之前,Ajax請求可能有點麻煩。寫一個簡單get請求,你可能會寫成:
01
$(function() {
02
$.get(
03
"content.txt",
04
function(resp) {
05
console.log("first code block");
06
console.log(resp);
07
}
08
);
09
10
});
但這種寫法存在一個問題:如果你不定義一個函數來運行此代碼,執行失敗後會發生什麼?在這個問題得到答案之前,我們還是先下載jQuery Deferred。本文將告訴你為什麼Deferred非常有用。(以下代碼依賴於jQuery1.5或更高版本)
jQuery 1.5以後,在調用jQuery的Ajax時會返回jQuery Deferred對象。文檔裡面說的不是很清楚,但簡單地說,調用Ajax返回了一個jQuery對象,它包含了promise:promise()方法會返回一個動態生成Promise。
在現實工作中,我們使用基本的Ajax調用,不需要關心它的內部運作,只需要關心調用成功或 失敗後的處理。我們繼續以上面的GET請求為例, 講解jQuery Deferred的when()、then()和fail()方法:
1
$.when($.get("content.txt"))
2
.then(function(resp) {
3
console.log("third code block, then() call");
4
console.log(resp);
5
})
6
.fail(function(resp) {
7
console.log(resp);
8
});
我們可以將上面代碼理解為:
1
$.when(some ajax request).then(do this if it succeeds).fail(or do this if it fails)
它的主要特點是 $.when()裡面可以寫多個函數,一旦這些函數執行完成,才會調用.then():
1
$.when(fn1(), fn2()).then().fail()
你可能沒有注意到這種方法的優勢所在,我們可以通過下面代碼進行比較。:
首先,通過$.get()得到一個變量
1
var xhrreq = $.get("content.txt");
然後,我們可以給這個變量定義.success和:.error方法
1
xhrreq.success(function(resp) {
2
console.log(resp);
3
});
4
xhrreq.error(function(resp) {
5
console.log(resp);
6
});
同樣,我們可以聲明多個函數去運行:
1
xhrreq.success(fn1);
2
xhrreq.success(fn2);
或者,更簡單的寫法:
1
xhrreq.success(fn1, fn2);
通過以上代碼對比,得出結論:jQuery Deferred的when()、then()、fail()方法能夠直接綁定Ajax調用後的事件;而且寫法簡潔,邏輯清晰。
最後,希望jQuery Deferred能在你調用jQuery Ajax時有所幫助。