jQuery: Automatically abort AjaxRequests on Page Unload?

后端 未结 5 1611
有刺的猬
有刺的猬 2020-12-06 05:48

Thanks for reading.

I\'ve noticed that if I have a page that has one or more ajax requests open, and I click a link to leave a page, or refresh it, it will wait for

5条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-06 06:10

    You have to persist all you ajax request and when page is being reloading abort all requests. Sample

    var _requests = [];
    
    var _abortAllRequests = function () {
        $(_requests).each(function (i, xhr) { xhr.abort(); });
    
        _requests = [];
    }
    
    $(window).on("beforeunload", function () { 
        _abortAllRequests();
    });
    

    somewhere in your code

     _requests.push($.ajax(...))
    

    Additionally you can pop done requests using $.ajaxSetup with events ajaxStart ajaxStop, but its up to you

提交回复
热议问题