[英]Abort all previous requests in jquery
I have a search box in my application. 我的应用程序中有一个搜索框。 In which I have to show results while user typing the word in search box.
我必须在用户在搜索框中键入单词时显示结果。 For this I need to abort all previous requests and show the result of last request in grid.
为此,我需要中止所有先前的请求并在网格中显示上一个请求的结果。
Because I am using grid, grid "beforeSend" event will override jquery beforeSend event. 因为我使用网格,网格“beforeSend”事件将覆盖jquery beforeSend事件。 So I used below code,
所以我使用下面的代码,
<script type="text/javascript">
$(function () {
$.xhrPool = [];
grid.Adaptor.prototype.beforeSend = function (jqXHR) {
$.xhrPool.push(jqXHR);
}
$.xhrPool.abortAll = function () {
$(this).each(function (i, jqXHR) {
jqXHR.abort();
$.xhrPool.splice(i, 1);
});
}
$.ajaxSetup({
complete: function (jqXHR) {
var i = $.xhrPool.indexOf(jqXHR);
if (i > -1) $.xhrPool.splice(i, 1);
}
});
})
However, I can push the request in xhrPool, but I can't abort the previous requests. 但是,我可以在xhrPool中推送请求,但我无法中止先前的请求。
Note $.xhrPool.abortAll = function () {
this is not hitting when I place a breakpoint. 注意
$.xhrPool.abortAll = function () {
当我放置一个断点时,这不会打。
What I am missing here ? 我在这里缺少什么?
I have to show results while user typing the word in search box.
我必须在用户在搜索框中输入单词时显示结果。 For this I need to abort all previous requests and show the result of last request in grid .
为此, 我需要中止所有先前的请求并在网格中显示上一个请求的结果 。
Your code: 你的代码:
$.ajaxSetup({
complete: function (jqXHR) {
var i = $.xhrPool.indexOf(jqXHR);
if (i > -1) $.xhrPool.splice(i, 1);
}
});
Won't do anything as this complete
callback fires only when the request has got the response as success
or error
. 不会做任何事情,因为只有当请求获得
success
或error
的响应时才会触发此complete
回调。 So, aborting here doesn't make sense. 所以,在这里堕胎没有意义。
I would suggest you to use a timed setTimeout()
in conjunction with clearTimeout()
: 我建议你使用一个定时的
setTimeout()
和clearTimeout()
:
$(function() {
var time;
$('input').keydown(function(e){
if(time){
// before hitting the ajax
// clear the timeout if there is/are
clearTimeout(time);
}
time = setTimeout(function(){
// here put the ajax code.
},600);
});
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.