使用 jQuery 中止 Ajax 请求 [英] Abort Ajax requests using jQuery

查看:38
本文介绍了使用 jQuery 中止 Ajax 请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能使用 jQuery,我取消/中止我尚未收到响应的 Ajax 请求?

Is it possible that using jQuery, I cancel/abort an Ajax request that I have not yet received the response from?

推荐答案

大多数 jQuery Ajax 方法返回一个 XMLHttpRequest(或等效的)对象,因此您只需使用 abort().

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

查看文档:

  • 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()

更新:从 jQuery 1.5 开始,返回的对象是名为 jqXHR 的原生 XMLHttpRequest 对象的包装器.该对象似乎公开了所有本机属性和方法,因此上面的示例仍然有效.请参阅jqXHR 对象(jQuery API 文档).

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).

更新 2:从 jQuery 3 开始,ajax 方法现在返回一个带有额外方法(如 abort)的 promise,因此上面的代码仍然有效,尽管返回的对象不再是 xhr.请参阅此处为 3.0 博客.

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.

UPDATE 3:xhr.abort() 仍然适用于 jQuery 3.x.不要假设 update 2 是正确的.有关 jQuery Github 存储库的更多信息.

UPDATE 3: xhr.abort() still works on jQuery 3.x. Don't assume the update 2 is correct. More info on jQuery Github repository.

这篇关于使用 jQuery 中止 Ajax 请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆