Stop all active ajax requests in jQuery

前端 未结 16 1045
自闭症患者
自闭症患者 2020-11-22 13:51

I have a problem, when submitting a form all active ajax request fail, and that triggers error event.

How to stop all active ajax requests in jQuery without trigerri

16条回答
  •  日久生厌
    2020-11-22 14:09

    I extended mkmurray and SpYk3HH answer above so that xhrPool.abortAll can abort all pending requests of a given url :

    $.xhrPool = [];
    $.xhrPool.abortAll = function(url) {
        $(this).each(function(i, jqXHR) { //  cycle through list of recorded connection
            console.log('xhrPool.abortAll ' + jqXHR.requestURL);
            if (!url || url === jqXHR.requestURL) {
                jqXHR.abort(); //  aborts connection
                $.xhrPool.splice(i, 1); //  removes from list by index
            }
        });
    };
    $.ajaxSetup({
        beforeSend: function(jqXHR) {
            $.xhrPool.push(jqXHR); //  add connection to list
        },
        complete: function(jqXHR) {
            var i = $.xhrPool.indexOf(jqXHR); //  get index for current connection completed
            if (i > -1) $.xhrPool.splice(i, 1); //  removes from list by index
        }
    });
    $.ajaxPrefilter(function(options, originalOptions, jqXHR) {
        console.log('ajaxPrefilter ' + options.url);
        jqXHR.requestURL = options.url;
    });
    

    Usage is same except that abortAll can now optionally accept a url as a parameter and will cancel only pending calls to that url

提交回复
热议问题