ajax的傳統寫法:
$.ajax({
url: "test.html",
success: function(){
alert("哈哈,成功了!");
},
error:function(){
alert("出錯啦!");
}
});
Jquery版本在1.5之前,返回的是XHR對象;當版本高於1.5之后,返回的是deferred對象,可以使用 done 和 fail。
所以新的寫法如下:
$.ajax("test.html")
.done(function(){ alert("哈哈,成功了!"); })
.fail(function(){ alert("出錯啦!"); });
可以有多個done,按照順序執行。
$.ajax("test.html")
.done(function(){ alert("哈哈,成功了!");} )
.fail(function(){ alert("出錯啦!"); } )
.done(function(){ alert("第二個回調函數!");} );
有時為了省事,可以把done()和fail()合在一起寫,這就是then()方法。
$.ajax("test.html")
.then(function(){ alert("哈哈,成功了!"); },
function(){ alert("出錯啦!"); }
);
$.when
為多個事件指定相同的回調:
$.when($.ajax("test1.html"),
$.ajax("test2.html"))
.done(function(){ alert("哈哈,成功了!"); })
.fail(function(){ alert("出錯啦!"); });
將普通的異步函數改裝成deferred對象來使用$.when:
var wait = function(){
setTimeout(function(){
alert("執行完畢!");
},5000);
};
在未改裝前使用無效:(原因在於$.when()的參數只能是deferred對象)
$.when(wait())
.done(function(){ alert("哈哈,成功了!"); })
.fail(function(){ alert("出錯啦!"); });
對wait()函數進行改裝:
var wait = function(){
let df = $.Deferred(); // 新建一個deferred對象
setTimeout(function(){
alert("執行完畢!");
df.resolve(); // 將df對象的執行狀態從"未完成"改為"已完成",從而觸發done()方法。
// df.reject(); // 將df對象的執行狀態從"未完成"改為"已失敗",從而觸發fail()方法。
},5000);
return df; // 現在返回的就是deferred對象了
};
然后就可以使用了:
$.when(wait())
.done(function(){ alert("哈哈,成功了!"); })
.fail(function(){ alert("出錯啦!"); });
參考鏈接
http://www.ruanyifeng.com/blog/2011/08/a_detailed_explanation_of_jquery_deferred_object.html