Delay JQuery Ajax (jqXHR) Request with done/fail/complete callbacks

北战南征 提交于 2019-12-11 05:38:00

问题


When I use success callback this solution works fine, but when I use .done() this fail, how I can retry send enqueued ajax request with original .done() .fail() and complete() registered callbacks?

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!");
        });

I wanna enqueue a ajax call (based in a condition) to resend later, but when a resend it, .done()/.fail() original callback must be called. With 'success' callback option this code works fine.


回答1:


I use this for delaying AJAX requests:

Global variant:

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 that affects only jQuery AJAX requests:

$(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;
    };
});

In jQuery solution, you can easily attach handlers to jqxhr done/fail/progress events.



来源:https://stackoverflow.com/questions/16338367/delay-jquery-ajax-jqxhr-request-with-done-fail-complete-callbacks

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!