1

当我使用成功回调时,此解决方案工作正常,但是当我使用 .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() 原始回调。使用“成功”回调选项,此代码可以正常工作。

4

1 回答 1

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 请求的变体:

$(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 done/fail/progress 事件。

于 2015-05-15T15:38:59.283 回答