如何停止通过$不用彷徨发送的jQuery Ajax请求?彷徨、jQuery、Ajax

2023-09-11 00:53:32 作者:奶油味拥抱

我想提出在输入框中使用$不用彷徨,只要用户键入的字符一个Ajax请求 我想中止previous Ajax调用,然后作出新的,有什么办法?

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?

修改

解决了!

我刚刚发现$不用彷徨的简写方式$阿贾克斯,因此它返回一个XHR,所以我们可以调用中止该变量。

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.

推荐答案

您可以使用 .abort()上XMLHtt prequest的 $不用彷徨的回报。

You can use .abort() on XMLHttpRequest that $.get returns.

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

//Abort request
req.abort()

从 jQuery.ajax()文档:

在$阿贾克斯()函数返回它创建的XMLHtt prequest对象。通常jQuery的处理在内部创造这个对象,但可以使用XHR选项来指定一个自定义的功能,生产制造商之一。返回的对象一般可以丢弃,但是观察和​​操纵请求提供一个较低级别的接口。尤其是在调用.abort()在对象上完成之前将暂停请求。

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.

更多关于 .abort():https://developer.mozilla.org/en/XMLHtt$p$pquest#abort

还有一个jQuery插件 AjaxQueue 处理多个Ajax请求并行进行。

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