AJAX:在表单字段中键入搜索的延迟 [英] AJAX: Delay for search on typing in form field
问题描述
在我的网站上,我使用JavaScript / AJAX进行搜索并在用户输入时显示结果。
On my website I use JavaScript/AJAX to do the search and show results while the user is still typing.
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]
}
但这可能会导致很多请求进入服务器。
But this could cause a lot of requests coming to the server.
因此我希望通过设置延迟来缓解服务器:
每当onkeyup事件发生时触发后,函数doSearch()应该显示ajax loading graphic并等待2秒。只有在这2秒内没有再次触发事件时,才能从PHP文件中获取结果。
Whenever the onkeyup event is fired, the function doSearch() should show an "ajax loading graphic" and wait for 2 seconds. Only if the event is NOT fired again during these 2 seconds, the results should be fetched from the PHP file.
有没有办法做到这一点?请问你能帮帮我吗?在此先感谢!
Is there any way to do this? Could you help me please? Thanks in advance!
推荐答案
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
}
这篇关于AJAX:在表单字段中键入搜索的延迟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!