2013-05-02 172 views
0

當我使用成功回調此解決方案工作正常,但是當我使用.done()這失敗,我怎麼可以重試發送入隊阿賈克斯請求原始.done ().fail()和complete()註冊回調?延遲JQuery Ajax(jqXHR)請求與完成/失敗/完成回調

var requestQueue = []; 
     $.ajaxSetup({ 
      cache: false, 
      beforeSend: function (jqXHR, options) {         
       if(true){ //any condition 'true' just demonstrate 
        requestQueue.push({request:jqXHR,options:options}); 
        //simulate process this queue later for resend the request 
        window.setTimeout(function(){ 
         //this will work with success callbak option, 
         //but with .done() the console.log("Well Done!"); 
         // will fail        
         $.ajax($.extend(requestQueue.pop().options, {global:false, beforeSend:null})); 
        }, 3000) 
        return false; 
       } 
      }   
     }); 
     $.ajax({ 
      url:"TesteChanged.html", 
      error: function(){ 
       console.log("Oh nooooo!"); 
      } 
     }).done(function(){ 
      console.log("Well Done!"); 
     }); 

我要排隊一個Ajax調用(基於在條件)後重新發送,但是當重新發送,.done()/。失敗()原回調函數必須被調用。 '成功'回調選項這個代碼工作正常。

+1

不確定你在問什麼,但你可以設置你的ajax對象的'context'屬性,它將被傳遞迴所有的回調函數。你可以存儲任何你想要的東西。 – 2013-05-02 12:51:55

+0

@JimCote我想入場一個ajax調用(基於條件)重新發送,但是當重新發送它時,必須調用.done()/。fail()原始回調,請嘗試執行我的代碼。當您使用成功選項時,它可以正常工作,但不會與.done()一起使用。 – 2013-05-02 13:20:32

+0

我只使用過ajax對象的'success'和'complete'屬性(就像你使用'error'一樣)。 – 2013-05-02 14:41:08

回答

0

我用這個延遲AJAX請求:

全球變種:

var origSend = XMLHttpRequest.prototype.send; 
XMLHttpRequest.prototype.send = function() { 
    var xhr = this; 
    var origArguments = arguments; 
    setTimeout(function() { 
     if (xhr.readyState === 1) { 
      origSend.apply(xhr, origArguments); 
     } 
    }, 1000); 
}; 

Vairant僅影響jQuery的AJAX請求:

$(document).ajaxSend(function (event, jqxhr, settings) { 
    var origXhrFunc = settings.xhr; 
    settings.xhr = function() { 
     var xhr = origXhrFunc(); 
     var origSend = xhr.send; 
     xhr.send = function() { 
      var origArguments = arguments; 
      setTimeout(function() { 
       if (xhr.readyState === 1) { 
        origSend.apply(xhr, origArguments); 
       } 
      }, 1000); 
     }; 
     return xhr; 
    }; 
}); 

在jQuery的解決方案,可以輕鬆連接處理程序到jqxhr完成/失敗/進度事件。