使用完成/失败/完成回调延迟JQuery Ajax(jqXHR)请求

当我使用成功回调时,这个解决方案工作正常,但是当我使用.done()这个失败时,我怎样才能重新发送带有原始.done()。fail()和complete()注册回调的入队ajax请求?

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()/。fail()原始回调。 使用’success’回调选项,此代码可以正常工作。

我使用它来推迟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); }; 

仅影响jQuery AJAX请求的Vairant:

 $(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完成/失败/进度事件。