javascript 如何停止通过 $.get 发送的 jquery ajax 请求?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4163875/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 10:33:43  来源:igfitidea点击:

how to stop jquery ajax request sent via $.get?

jqueryajaxjavascript

提问by Shaheer

i am making a ajax request using $.get as soon as the user types a character in the input box i want to abort the previous ajax calls and then make the new one, is there a way?

我正在使用 $.get 发出 ajax 请求,只要用户在输入框中输入一个字符,我想中止之前的 ajax 调用,然后进行新的调用,有没有办法?

edit

编辑

solved!

解决了!

i just found out that $.get is a shorthand way to $.ajax and hence it returns a XHR and so we can call abort on that variable.

我刚刚发现 $.get 是 $.ajax 的简写方式,因此它返回一个 XHR,因此我们可以对该变量调用 abort。

回答by thaedal

You can use .abort()on XMLHttpRequest that $.getreturns.

您可以.abort()$.get返回的XMLHttpRequest 上使用。

var req = $.get('ajax/test.html', function(data) {
            $('.result').html(data);
            alert('Load was performed.');
          });

//Abort request
req.abort()

From jQuery.ajax()documentation:

来自jQuery.ajax()文档:

The $.ajax() function returns the XMLHttpRequest object that it creates. Normally jQuery handles the creation of this object internally, but a custom function for manufacturing one can be specified using the xhr option. The returned object can generally be discarded, but does provide a lower-level interface for observing and manipulating the request. In particular, calling .abort() on the object will halt the request before it completes.

$.ajax() 函数返回它创建的 XMLHttpRequest 对象。通常 jQuery 在内部处理此对象的创建,但可以使用 xhr 选项指定用于制造的自定义函数。返回的对象通常可以被丢弃,但确实提供了一个较低级别的接口来观察和操作请求。特别是,在对象上调用 .abort() 将在请求完成之前停止请求。

More on .abort(): XMLHttpRequest.abort()

更多关于.abort()XMLHttpRequest.abort()

There is also jQuery plugin AjaxQueuefor handling multiple Ajax request made in parallel.

还有 jQuery 插件AjaxQueue用于处理并行发出的多个 Ajax 请求。