AJAX:在表单字段中输入时延迟搜索

AJAX: Delay for search on typing in form field

本文关键字:输入 时延 延迟 搜索 字段 表单 AJAX      更新时间:2023-09-26

在我的网站上,我使用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()再次删除它

<form action="" method="post" accept-charset="utf-8">
    <p><input type="text" name="q" id="q" value="" onkeyup="doDelayedSearch(this.value)" /></p>
</form>
Javascript

var timeout = null;
function doDelayedSearch(val) {
  if (timeout) {  
    clearTimeout(timeout);
  }
  timeout = setTimeout(function() {
     doSearch(val); //this is your existing function
  }, 2000);
}

对于这类事情,我倾向于使用Remy Sharp创建的一个狡猾的小'throttling'函数:

http://remysharp.com/2010/07/21/throttling-function-calls/