这是使用'onkeyup'搜索时中止多个请求的正确方法。
(注意:对于多个请求,我指的是为字符串的每个字符创建顺序请求。例如:“Hello”创建'H','他',......'Hello' - 5个不同的请求)
var insideReq = false; /* Initialise to false */
$('#search').keyup( function() {
var SearchString = $('#search').val();
if((SearchString.length) >= 3) {
if(insideReq == true ) /* Check if somebody is inside */
ajaxReq.abort(); /* If yes, then throw her out */
insideReq = true; /* Inform I am inside */
var ajaxReq = $.get('search.exec.php', {q: SearchString}, function(ajaxContent) {
$('#container-list').html("<img src=\"img\\busy.gif\" class=\"busy-indicator\"/>");
$('#container-list').fadeOut(5);
$('#container-list').html(ajaxContent);
$('#container-list').fadeIn(1500);
insideReq = false; /* Work done; I am going */
});
}
});
答案 0 :(得分:2)
看起来不错。很少有代码优化技术可以让您的代码快速执行。
var insideReq = false; /* Initialise to false */
$('#search').keyup( function() {
var SearchString = $('#search').val();
if((SearchString.length) >= 3) {
if(insideReq == true ) /* Check if somebody is inside */
ajaxReq.abort(); /* If yes, then throw her out */
insideReq = true; /* Inform I am inside */
var ajaxReq = $.get('search.exec.php', {q: SearchString}, function(ajaxContent) {
$('#container-list')
.html("<img src=\"img\\busy.gif\" class=\"busy-indicator\"/>");
.fadeOut(5);
.html(ajaxContent);
.fadeIn(1500);
insideReq = false; /* Work done; I am going */
});
}
});
答案 1 :(得分:1)
当有人STOPS打字时你想要这个。创建一个300毫秒的计时器。在每次击键时清除并重置计时器。当计时器超时时,激活你的AJAX请求。