對于$.ajax請求來說,如果層級比較多,程序看起來會比較亂,而為了解決這種問題,才有了$when...done...fail...then的封裝,它將$.ajax這嵌套結構轉成了順序平行的結果,向下面的$.ajax寫法,看起來很亂
$.ajax({url: "/home/GetProduct",dataType: "JSON",type: "GET",success: function (data) {$.ajax({url: "/home/GetProduct",dataType: "JSON",type: "GET",success: function (data) {$.ajax({url: "/home/GetProduct",dataType: "JSON",type: "GET",success: function (data) {}}}
而它實現的功能無非就是外層執行完成后,去執行內層的代碼代碼,看下面的$.when寫法,就清晰多了
$.when($.ajax({url: "/home/GetProduct",dataType: "JSON",type: "GET",success: function (data) {alert(JSON.stringify(data));}})).done(function (data) {alert(data[0].Name);}).done(function (data) {alert(data[1].Name);}).fail(function () {alert("程序出現錯誤!");}).then(function (data) {alert("程序執行完成");});
而對于這種ajax的封裝,在比較流行的node.js里也需要被看到,這就類似于方法的回調技術!
在使用MVVM的KO上,更加得心應手,感覺$.when就是為了Knockoutjs而產生的!
//MVVM數據綁定var MyModel = new model();$.when($.ajax({url: "/home/GetProduct",dataType: "JSON",type: "GET",success: function (data) {MyModel.PeopleList = ko.observableArray(data);//先為對象賦值}})).done(function (data) {ko.applyBindings(MyModel);//再綁定對象});
以后我們在進行前端開發時,應該多使用這種順序的,平行的代碼段,而少用嵌套的代碼段,這只是大叔個人的見解。
下面通過一個例子再給大家介紹jquery when then(done) 用法
//運行條件jquery 1.82以上,直接運行代碼,看結果
var log = function(msg){ window.console && console.log(msg) } function asyncThing1(){ var dfd = $.Deferred(); setTimeout(function(){ log('asyncThing1 seems to be done...'); dfd.resolve('1111'); },1000); return dfd.promise(); } function asyncThing2(){ var dfd = $.Deferred(); setTimeout(function(){ log('asyncThing2 seems to be done...'); dfd.resolve('222'); },1500); return dfd.promise(); } function asyncThing3(){ var dfd = $.Deferred(); setTimeout(function(){ log('asyncThing3 seems to be done...'); dfd.resolve('333'); },2000); return dfd.promise(); } /* do it */ $.when( asyncThing1(), asyncThing2(), asyncThing3() ).done(function(res1, res2, res3){ log('all done!'); log(res1 + ', ' + res2 + ', ' + res3); })
以上所述是小編給大家介紹的Jquery $when done then的用法詳解,希望對大家有所幫助,如果大家對此還有疑問歡迎給我留言,小編會及時回復大家的,在此也非常感謝大家對武林網網站的支持!
新聞熱點
疑難解答