Stop all active ajax requests in jQuery

前端 未结 16 905
自闭症患者
自闭症患者 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:34

    I have updated the code to make it works for me

    $.xhrPool = [];
    $.xhrPool.abortAll = function() {
        $(this).each(function(idx, jqXHR) {
            jqXHR.abort();
        });
        $(this).each(function(idx, jqXHR) {
            var index = $.inArray(jqXHR, $.xhrPool);
            if (index > -1) {
                $.xhrPool.splice(index, 1);
            }
        });
    };
    
    $.ajaxSetup({
        beforeSend: function(jqXHR) {
            $.xhrPool.push(jqXHR);
        },
        complete: function(jqXHR) {
            var index = $.inArray(jqXHR, $.xhrPool);
            if (index > -1) {
                $.xhrPool.splice(index, 1);
            }
        }
    });
    
    0 讨论(0)
  • 2020-11-22 14:35

    Every time you create an ajax request you could use a variable to store it:

    var request = $.ajax({
        type: 'POST',
        url: 'someurl',
        success: function(result){}
    });
    

    Then you can abort the request:

    request.abort();
    

    You could use an array keeping track of all pending ajax requests and abort them if necessary.

    0 讨论(0)
  • 2020-11-22 14:35

    I had some problems with andy's code, but it gave me some great ideas. First problem was that we should pop off any jqXHR objects that successfully complete. I also had to modify the abortAll function. Here is my final working code:

    $.xhrPool = [];
    $.xhrPool.abortAll = function() {
                $(this).each(function(idx, jqXHR) {
                            jqXHR.abort();
                            });
    };
    $.ajaxSetup({
        beforeSend: function(jqXHR) {
                $.xhrPool.push(jqXHR);
                }
    });
    $(document).ajaxComplete(function() {
                $.xhrPool.pop();
                });
    

    I didn't like the ajaxComplete() way of doing things. No matter how I tried to configure .ajaxSetup it did not work.

    0 讨论(0)
  • 2020-11-22 14:36

    Better to use independent code.....

    var xhrQueue = []; 
    
    $(document).ajaxSend(function(event,jqxhr,settings){
        xhrQueue.push(jqxhr); //alert(settings.url);
    });
    
    $(document).ajaxComplete(function(event,jqxhr,settings){
        var i;   
        if((i=$.inArray(jqxhr,xhrQueue)) > -1){
            xhrQueue.splice(i,1); //alert("C:"+settings.url);
        }
    });
    
    ajaxAbort = function (){  //alert("abortStart");
        var i=0;
        while(xhrQueue.length){ 
            xhrQueue[i++] .abort(); //alert(i+":"+xhrQueue[i++]);
        }
    };
    
    0 讨论(0)
提交回复
热议问题