jQuery的deferred對象

    /**
     * 一、普通請求
     **/
    // $.ajax({
    //     url:"a.html",
    //     success: function(data){
    //         console.log(data)
    //         $("#box").html(data)
    //     },
    //     error:function(){
    //         alert("error")
    //     }
    // })


    /**
     * 二、同一操做多回調
     **/
    // $.ajax('a.html')
    // .done(function (data) {
    //     alert("a")
    //     $("#box").html(data)
    // })
    // .fail(function (data) {
    //     console.log("fail")
    // })
    // .done(function (data) {
    //     alert("b")
    //     $("#box").append('done2222')
    // })


    /**
     * 三、 多個請求,同一回調
     **/
     // $.when($.ajax('a.html'),$.ajax('b.html'))
     // .done(function (dataA,dataB) {
     //     // for(i in data){
     //     //     console.log(data[i])
     //     // }
     //     console.log("a--",dataA[0])
     //     console.log("b--",dataB[0])
     // })
     // .fail(function (data) {
     //     console.log("error")
     // })
    
     /**
     * 四、 耗時操做; 如何讓耗時比較久的請求,按順序出牌
     **/
     // var wait = function (){
     //     var task = function () {
     //         console.log("wait還沒完呢; 假設的耗時請求完畢")
     //     }
     //     setTimeout(task,3000)
     // }
     // $.when(wait())
     // .done(function (data) {
     //     console.log("這是done操做; wait操做,3秒耗時完成了麼???",data)
     // })
     // .fail(function () { console.log("error") })
     //done方法會馬上執行,wait還沒完成,done是得不到回調的。
     //緣由是$.when()的參數只能是 deferred 對象
     //因此必須對 wait() 改寫
    
     //改寫 例子 1、
     // var wait = function (delay) {
     //     var task = function () {
     //         $.ajax({
     //             url: 'a.html',
     //             success:function (data) {
     //                 console.log("wait",data)
     //             }
     //         })
     //     }
     //     setTimeout(task, 3000)
     //     return delay;
     // }
     // $.when(wait(delay))
     // .done(function (data) {
     //     console.log("成功了麼?",data)
     // })
     // .fail(function () { console.log("error") })

    //改寫 例子 2、
     var delay = $.Deferred();
     var wait = function (delay) {
         $.ajax({
             url: 'a.html',
             success:function (data) {
                 // console.log("success",data)
                 $("#box").append("<p>AAAAAA</p>")
                 var task = function () {
                     console.log("task: wait 3秒吧。")
                 }
                 delay.resolve();//delay對象的執行狀態從"未完成"改成"已完成",從而觸發done()方法。
                 setTimeout(task,3000)
             }
         })
     }
     $.when(wait(delay))
     .done(function (data) {
         console.log(".done: ",delay)
         console.log(".promise: ",delay.promise())
         $("#box").append("<p>BBBBBB</p>")
     })
    
     /**
     * 四、 執行狀態-deferred.resolve()和deferred.reject()
     * deferred.reject()deferred對象的執行狀態從"未完成"改成"已失敗",從而觸發fail()方法。
     **/html

 

注:整理自   阮一峯的網絡日誌jquery

相關文章
相關標籤/搜索