AJAX:在表单字段中输入时延迟搜索 [英] AJAX: Delay for search on typing in form field

查看:21
本文介绍了AJAX:在表单字段中输入时延迟搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的网站上,我使用 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 加载图形"并等待 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆