AJAX:在表单字段中键入搜索的延迟

caw*_*caw 37 javascript forms ajax input

在我的网站上,我使用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>
Run Code Online (Sandbox Code Playgroud)

JavaScript(标题):

function doSearch(text) {
    // do the ajax stuff here
    // call getResults.php?search=[text]
}
Run Code Online (Sandbox Code Playgroud)

但这可能会导致很多请求进入服务器.

因此,我希望通过设置延迟来减轻服务器的负担:

每当触发onkeyup事件时,函数doSearch()应显示"ajax加载图形"并等待2秒.只有在这2秒内未再次触发事件时,才应从PHP文件中获取结果.

有没有办法做到这一点?请问你能帮帮我吗?提前致谢!

Mik*_*rds 108

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
}
Run Code Online (Sandbox Code Playgroud)


Jon*_*øgh 16

只需使用setTimeout()设置延迟调用,然后使用clearTimeout()在每个事件上再次删除它

HTML

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

使用Javascript

var timeout = null;

function doDelayedSearch(val) {
  if (timeout) {  
    clearTimeout(timeout);
  }
  timeout = setTimeout(function() {
     doSearch(val); //this is your existing function
  }, 2000);
}
Run Code Online (Sandbox Code Playgroud)


And*_*ume 5

对于这种类型的事情,我倾向于使用 Remy Sharp 创建的一个狡猾的小“节流”函数:

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