Abort Ajax requests using jQuery

使用jQuery,我如何取消/中止我还没有收到响应的Ajax请求


Most of the jQuery Ajax methods return an XMLHttpRequest (or the equivalent) object, so you can just use abort() .

See the documentation:

  • abort Method (MSDN). Cancels the current HTTP request.
  • abort() (MDN). If the request has been sent already, this method will abort the request.
  • var xhr = $.ajax({
        type: "POST",
        url: "some.php",
        data: "name=John&location=Boston",
        success: function(msg){
           alert( "Data Saved: " + msg );
        }
    });
    
    //kill the request
    xhr.abort()
    

    UPDATE: As of jQuery 1.5 the returned object is a wrapper for the native XMLHttpRequest object called jqXHR. This object appears to expose all of the native properties and methods so the above example still works. See The jqXHR Object (jQuery API documentation).

    UPDATE 2: As of jQuery 3, the ajax method now returns a promise with extra methods (like abort), so the above code still works, though the object being returned is not an xhr any more. See the 3.0 blog here.


    You can't recall the request but you can set a timeout value after which the response will be ignored. See this page for jquery AJAX options. I believe that your error callback will be called if the timeout period is exceeded. There is already a default timeout on every AJAX request.

    You can also use the abort() method on the request object but, while it will cause the client to stop listening for the event, it may probably will not stop the server from processing it.


    It's an asynchronous request, meaning once it's sent it's out there.

    In case your server is starting a very expensive operation due to the AJAX request, the best you can do is open your server to listen for cancel requests, and send a separate AJAX request notifying the server to stop whatever it's doing.

    Otherwise, simply ignore the AJAX response.

    链接地址: http://www.djcxy.com/p/12436.html

    上一篇: 使用ASP.NET MVC的json请求的401响应代码

    下一篇: 使用jQuery中止Ajax请求