问题
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.
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();
});
});
回答1:
This has already been answered in the ultimate-uber-authoritative thread here.
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.
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."
I've run into the same issues doing ajax suggest lookups ;)
回答2:
You just have to save the returning value of each request you send and, before adding a new one, just do a savedRequest.abort()
first.
来源:https://stackoverflow.com/questions/8072698/jquery-keyup-ajax-request-kill-previous-requests