e.g。在用户输入某些文本的搜索表单中,当时,AJAX请求应发送每个keyup事件,搜索键为查询字符串。搜索键将是输入框中的值。
如果用户输入" ABCD",在这种情况下,前3个AJAX请求应该被杀/取消,因为在第4个AJAX请求中,searchkey将是" ABCD"
$(document).ready(function(){
$("#searchInput").keyup(function(){
ajaxSearch( $("#searchInput").val() );
});
});
在keyup事件中,我调用了" ajaxSearch()"功能
function ajaxSearch(searchKey) {
$.ajax({
type: "get",
url: "http://example.com/ajaxRequestHandler/",
data: "action=search&searchkey=" + searchKey
}).done(function() {
/* process response */
});
}
答案 0 :(得分:5)
var request;
function ajaxSearch(searchKey) {
/* if request is in-process, kill it */
if(request) {
request.abort();
};
request = $.ajax({
type: "get",
url: "http://example.com/ajaxRequestHandler/",
data: "action=search&searchkey=" + searchKey
}).done(function() {
/* process response */
/* response received, reset variable */
request = null;
});
}
答案 1 :(得分:1)
为了避免多个ajax请求;我们可以参考和实现David Walsh's Blog post.中提到的去抖动功能。它对Underscore.js的去抖动功能的实现有一些深刻的见解。防弹跳功能只会在不到一秒的时间内触发一次,而不是像触发时一样快。它肯定有助于限制连续的网络请求。
// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
var ajaxSearch = debounce(function() {
//send an AJAX network request.
$.ajax({
type: "get",
url: "http://example.com/ajaxRequestHandler/",
data: "action=search&searchkey=" + searchKey
}).done(function() {
/* process response */
});
//250 indicates the minimum tie interval between the series of events being fired
}, 250);
$("#searchInput").keyup(function(){
ajaxSearch($("#searchInput").val());
});
答案 2 :(得分:0)
在Atul Bhosale的回答中,当用户输入" ABCD"时,仍有四个请求。这只是输入服务器的速度和响应时间的问题。
最好使用超时。在这种情况下,如果用户"完成/超时"则仅发送请求。打字:
$("#searchInput").keyup(function(){
var value = $(this).val();
setTimeout( function() { ajaxSearch(value) }, 300 );
});
只是玩弄超时。对我来说300毫秒很好......