jQuery Keyup Ajax请求:杀死以前的请求 [英] jQuery Keyup Ajax Request: Kill previous requests
问题描述
我有一个脚本在我的搜索输入框上的keyup事件上执行ajax请求。我在Firefox中注意到(我正在查看控制台)每个被发送的请求都会完成。所以有大量的ajax请求发生。
I have a script that does an ajax request out on a keyup event on my search input box. I am noticing in Firefox (I am looking at the console) that every request that is sent off finishes. So there are a ton of ajax requests that happen.
在keyup事件中是否有杀死正在进行的ajax请求?
Is there anyway to kill an ajax request in progress upon a keyup event?
jQuery:
jQuery(function() {
var request;
request = function(url, keyword) {
return $.post('/backpack/' + url + '/search?keyword=' + keyword, function(data) {
var el;
el = "#result_" + url;
return $(el).html(data);
});
};
$("#search_text").bind("keyup", function() {
var query, url, _i, _len, _ref;
query = $(this).val();
if (query.length > 2) {
_ref = ['tracks', 'albums', 'artists'];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
url = _ref[_i];
request(url, query);
}
return $("#search_suggestions").show();
} else {
return $("#search_suggestions").hide();
}
});
return $("#suggestion_all_results").bind("click", function() {
return $('#search_form form').submit();
});
});
推荐答案
这已在这里的第三方 - 授权线程。
简答:它返回一个XHR对象,你可以调用 abort()
Short answer: it returns an XHR object and you can call abort()
如果你在发送密钥事件时,您可能还会考虑添加延迟;这对你的服务器来说是一个相当大的负荷,所以等到你打扰事件之前等待几秒钟之间的暂停。
If you are sending on keyup events, you might also think about adding a delay; it's going to be a pretty big load on your server, so wait for a pause of a few seconds between strokes before you bother kicking off the event.
正如Erv Walter所说在上面的线程的评论中:值得注意的是,如果服务器已经收到请求,它可能会继续处理请求(取决于服务器的平台),即使浏览器不再监听响应。没有可靠的通过处理正在进行的请求使Web服务器停止运行的方法。
As Erv Walter said in the above thread's comments: "Of note, if the server has already received the request, it may continue processing the request (depending on the platform of the server) even though the browser is no longer listening for a response. There is no reliable way to make the web server stop in its tracks with processing a request that is in progress."
我遇到了同样的问题,做了ajax建议查找;)
I've run into the same issues doing ajax suggest lookups ;)
这篇关于jQuery Keyup Ajax请求:杀死以前的请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!