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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7849221/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 03:49:34  来源:igfitidea点击:

AJAX: Delay for search on typing in form field

javascriptajaxformsinput

提问by caw

On my website I use JavaScript/AJAX to do the search and show results while the user is still typing.

在我的网站上,我使用 JavaScript/AJAX 进行搜索并在用户仍在输入时显示结果。

HTML (body):

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 (header):

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.

但这可能会导致大量请求进入服务器。

Thus I want to relieve the server by setting up a delay:

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

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.

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

Is there any way to do this? Could you help me please? Thanks in advance!

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

回答by Mike Richards

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
}

回答by Jonas H?gh

Simply setup the delayed invocation with setTimeout(), then remove it again on every event with clearTimeout()

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

HTML

HTML

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

Javascript

Javascript

var timeout = null;

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

回答by Andy Hume

For this type of thing I tend to use a cunning little 'throttling' function created by Remy Sharp:

对于这种类型的事情,我倾向于使用 Remy Sharp 创建的一个巧妙的小“节流”功能:

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

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