Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
211 views
in Technique[技术] by (71.8m points)

javascript - 使用jQuery中止Ajax请求(Abort Ajax requests using jQuery)

使用jQuery,如何取消/中止尚未收到响应的Ajax请求

  ask by lukewm translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Most of the jQuery Ajax methods return an XMLHttpRequest (or the equivalent) object, so you can just use abort() .(大多数jQuery Ajax方法都返回XMLHttpRequest(或等效的)对象,因此您可以使用abort() 。)

See the documentation:(请参阅文档:)

  • abort Method ( MSDN ).(中止方法MSDN )。) Cancels the current HTTP request.(取消当前的HTTP请求。)
  • abort() ( MDN ).(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.(更新:从jQuery 1.5开始,返回的对象是名为jqXHR的本机XMLHttpRequest对象的包装。)

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).(请参阅jqXHR对象 (jQuery API文档)。)

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.(更新2:从jQuery 3开始,ajax方法现在会返回带有其他方法的promise(例如abort),因此上面的代码仍然有效,尽管返回的对象不再是xhr 。)

See the 3.0 blog here .(在此处查看3.0博客 。)

UPDATE 3 : xhr.abort() still works on jQuery 3.x.(更新3xhr.abort()仍适用于xhr.abort() 。)

Don't assume the update 2 is correct.(不要以为更新2是正确的。) More info on jQuery Github repository .(有关jQuery Github存储库的更多信息 。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...