How to cancel/abort jQuery AJAX request?

后端 未结 8 2029
时光说笑
时光说笑 2020-11-22 09:30

I\'ve an AJAX request which will be made every 5 seconds. But the problem is before the AJAX request if the previous request is not completed I\'ve to abort that request and

8条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 10:19

    The jquery ajax method returns a XMLHttpRequest object. You can use this object to cancel the request.

    The XMLHttpRequest has a abort method, which cancels the request, but if the request has already been sent to the server then the server will process the request even if we abort the request but the client will not wait for/handle the response.

    The xhr object also contains a readyState which contains the state of the request(UNSENT-0, OPENED-1, HEADERS_RECEIVED-2, LOADING-3 and DONE-4). we can use this to check whether the previous request was completed.

    $(document).ready(
        var xhr;
    
        var fn = function(){
            if(xhr && xhr.readyState != 4){
                xhr.abort();
            }
            xhr = $.ajax({
                url: 'ajax/progress.ftl',
                success: function(data) {
                    //do something
                }
            });
        };
    
        var interval = setInterval(fn, 500);
    );
    

提交回复
热议问题