How can I abort an AJAX call?

This question already has an answer here:

  • Abort Ajax requests using jQuery 18 answers

  • You need to assign your ajax request to variable,

    var xhr = $.ajax({
    ***
    });
    

    then call abort()

    xhr.abort();
    

    In a single use of AJAX it is simple. The XMLHttpRequest has a abort method, which cancels the request.

    // creating our request
    xhr = $.ajax({
    url: 'ajax/progress.ftl',
    success: function(data) {
    //do something
    }
    });
    
    // aborting the request
    xhr.abort();
    

    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). So we can use this to check whether the previous request was completed.

    // abort function with check readystate
    function abortAjax(xhr) {
    if(xhr && xhr.readystate != 4){
    xhr.abort();
    }
    }
    
    // this function usage
    abortAjax(xhr);
    
    链接地址: http://www.djcxy.com/p/71934.html

    上一篇: 我可以/如何明确终止长时间运行的xhr请求?

    下一篇: 我如何中止AJAX呼叫?