Stop all active ajax requests in jQuery

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

    Just as important: say you want to log off and you are generating new requests with timers: because session data is renewed with each new bootstrap (maybe you can tell I am talking Drupal, but this could be any site that uses sessions)... I had to go through all my scripts with a search and replace, cause I had a ton of stuff running in different cases: global variables at the top:

    var ajReq = [];
    var canAj = true;
    function abort_all(){
     for(x in ajReq){
        ajReq[x].abort();
        ajReq.splice(x, 1)
     }
     canAj = false;
    }
    function rmvReq(ranNum){
     var temp = [];
     var i = 0;
     for(x in ajReq){
        if(x == ranNum){
         ajReq[x].abort();
         ajReq.splice(x, 1);
        }
        i++;
     }
    }
    function randReqIndx(){
     if(!canAj){ return 0; }
     return Math.random()*1000;
    }
    function getReqIndx(){
     var ranNum;
     if(ajReq.length){
        while(!ranNum){
         ranNum = randReqIndx();
         for(x in ajReq){
        if(x===ranNum){
         ranNum = null;
        }
         }
        }
        return ranMum;
     }
     return randReqIndx();
    }
    $(document).ready(function(){
     $("a").each(function(){
        if($(this).attr('href').indexOf('/logout')!=-1){          
         $(this).click(function(){
        abort_all();                 
         });
        }
     })
    });
    // Then in all of my scripts I wrapped my ajax calls... If anyone has a suggestion for a 
        // global way to do this, please post
    var reqIndx = getReqIndx();
    if(reqIndx!=0){
    ajReq[reqIndx] = $.post(ajax, { 'action': 'update_quantities', iids:iidstr, qtys:qtystr },  
    function(data){
     //..do stuff
     rmvReq(reqIndx);
     },'json');
    }
    

提交回复
热议问题