2013-05-02 178 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完成/失败/进度事件。