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

时间:2013-05-02 12:41:57

标签: jquery ajax jqxhr

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

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()原始回调。使用“成功”回调选项,此代码可以正常工作。

1 个答案:

答案 0 :(得分:1)

我用它来推迟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完成/失败/进度事件。