gpt4 book ai didi

javascript - 中止 jquery 中的所有先前请求

转载 作者:行者123 更新时间:2023-11-29 15:29:30 25 4
gpt4 key购买 nike

我的应用程序中有一个搜索框。当用户在搜索框中键入单词时,我必须在其中显示结果。为此,我需要中止所有先前的请求并在网格中显示最后一个请求的结果。

因为我正在使用网格,网格“beforeSend”事件将覆盖 jquery beforeSend 事件。所以我使用了下面的代码,

<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);
}
});
})

但是,我可以在xhrPool中推送请求,但是我不能中止之前的请求。

注意 $.xhrPool.abortAll = function () { 当我放置断点时,它没有命中。

我在这里缺少什么?

最佳答案

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.

您的代码:

$.ajaxSetup({
complete: function (jqXHR) {
var i = $.xhrPool.indexOf(jqXHR);
if (i > -1) $.xhrPool.splice(i, 1);
}
});

不会执行任何操作,因为此 complete 回调仅在请求获得 successerror 响应时触发。所以,在这里中止是没有意义的。

我建议您将定时 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);

});

})

关于javascript - 中止 jquery 中的所有先前请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36148366/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com