AJAX:在表单字段中输入时延迟搜索
AJAX: Delay for search on typing in form field
在我的网站上,我使用JavaScript/AJAX进行搜索并显示结果,而用户仍在输入。
HTML(身体):
<form action="" method="post" accept-charset="utf-8">
<p><input type="text" name="q" id="q" value="" onkeyup="doSearch(this.value)" /></p>
</form>
JavaScript(头):
function doSearch(text) {
// do the ajax stuff here
// call getResults.php?search=[text]
}
但是这会导致大量的请求到达服务器。
因此,我想通过设置延迟来缓解服务器:
当onkeyup事件被触发时,doSearch()函数应该显示一个"ajax加载图形"并等待2秒。只有当事件在这2秒内没有再次触发时,才会从PHP文件中获取结果。
有什么办法可以做到吗?你能帮我一下吗?提前感谢!
var delayTimer;
function doSearch(text) {
clearTimeout(delayTimer);
delayTimer = setTimeout(function() {
// Do the ajax stuff
}, 1000); // Will do the ajax stuff after 1000 ms, or 1 s
}
只需使用setTimeout()设置延迟调用,然后在每个事件上使用clearTimeout()再次删除它