jQuery检查wordchange而不是";更改“;触发
我有一个输入,用户在其中键入一个搜索参数,现在我将它设置为keyup,以便对返回搜索结果的PHP脚本执行POST-ajax请求。然而,它在大约10秒内(用户输入时)发出了500亿个post请求(不是字面意义上的),这减慢了整个体验。我可以使用jQuery通过检测空格键的使用来检测“wordup”而不是“keyup”吗jQuery检查wordchange而不是";更改“;触发,jquery,ajax,keyboard,onkeyup,Jquery,Ajax,Keyboard,Onkeyup,我有一个输入,用户在其中键入一个搜索参数,现在我将它设置为keyup,以便对返回搜索结果的PHP脚本执行POST-ajax请求。然而,它在大约10秒内(用户输入时)发出了500亿个post请求(不是字面意义上的),这减慢了整个体验。我可以使用jQuery通过检测空格键的使用来检测“wordup”而不是“keyup”吗 这有意义吗?当用户在特定时间段内停止键入时,您可以使用类似延迟的方式 也许是这样的?您还可以添加额外的功能来触发空格键按下。(这只是用于谷歌风格的insta搜索,因此可能/可能没有
这有意义吗?当用户在特定时间段内停止键入时,您可以使用类似延迟的方式 也许是这样的?您还可以添加额外的功能来触发空格键按下。(这只是用于谷歌风格的insta搜索,因此可能/可能没有帮助)
有关此功能的更多信息,请参阅。您当然可以;您可以在本地检测keyup事件并检查它们的空间
但是,如果您能够设法获得与前缀匹配的所有搜索结果,并将其发送到数据结构中的javascript,那么您将获得更多的优势。查看“数字搜索树”(也称为“尝试”)了解详细信息。我将此作为一个单独的答案添加,因为它与我的第一个答案完全不同
$('#yourinput').keyup(function(){
var input = this,
timer = $.data(this, 'timer'),
lastrequest = $.data(this, 'lastrequest');
if (timer) { // if there is a keyup timeout still pending, cancel it
clearTimeout(timer);
$.data(this, 'timer', 0);
}
if (lastrequest) { // if there is an AJAX request still running, abort it
lastrequest.abort();
$.data(this, 'lastrequest', false);
}
timer = setTimeout(function(){
lastrequest = $.post({ // or whatever your AJAX call is...
url: 'yourfile',
data: { search: input.value },
success: function(response){
lastrequest = false;
// handle response here
}
});
$.data(input, 'lastrequest', lastrequest);
}, 500);
$.data(this, 'timer', timer);
});
一个人也不会开枪word@German当前位置不管OPs建议的解决方案有多可怕,它确实回答了这个问题。是的,没错-我需要单词搜索!好主意though@benhowdle89这是你的主意!:-)@本豪德89看到我的另一个答案:-)这一个我会投赞成票。如果你愿意,可以叫我
.data()
瘾君子,但是你可以使用这个方便的函数,而不是创建全局变量。谢谢你的.abort
-我没想过。我试着写这样的东西,但你也打败了我:这里有一个fiddle@German Good call on$。data
;我添加了它。有点笨重,但你看。。。
$('#yourinput').keyup(function(e) {
if (e.which == 32) { // space key pressed
// do your AJAX here
}
});
$('#yourinput').keyup(function(){
var input = this,
timer = $.data(this, 'timer'),
lastrequest = $.data(this, 'lastrequest');
if (timer) { // if there is a keyup timeout still pending, cancel it
clearTimeout(timer);
$.data(this, 'timer', 0);
}
if (lastrequest) { // if there is an AJAX request still running, abort it
lastrequest.abort();
$.data(this, 'lastrequest', false);
}
timer = setTimeout(function(){
lastrequest = $.post({ // or whatever your AJAX call is...
url: 'yourfile',
data: { search: input.value },
success: function(response){
lastrequest = false;
// handle response here
}
});
$.data(input, 'lastrequest', lastrequest);
}, 500);
$.data(this, 'timer', timer);
});