执行Ajax搜索多的keydown事件一秒钟后 [英] Perform AJAX search one second after multiple keydown events

查看:300
本文介绍了执行Ajax搜索多的keydown事件一秒钟后的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我想提出一个自动完成的jQuery 。阿贾克斯是用来获得重XML从远程位置文件。如果我搜索前。 好汉两个半它大约16 querys (对于每一个字母输入,除了3首,看code)与阿贾克斯。

So I am making a autocomplete with jquery. Ajax is used to get a heavy xml file from remote location. If I search for ex. "Two and a half men" it does about 16 querys (for every letter typed except the 3 first, look the code) with ajax.

我希望它的做Ajax请求一秒钟之后用户pressed最后的关键所以它会做的,而不是16一个查询。

I want it to do the Ajax request a second after user has pressed the last key so it will do one query instead of 16.

因此​​,如果用户presses另一个键之前,它一直自上次keydown事件1秒,也不会做查询呢。

So if user presses another key before it's been 1 second since the last keydown event, it won't do the query yet.

<script>
    $(document).ready(function(){
        $('#tv_search').keydown(function(){
            var search = $(this).val();
            if(search.length >= 3)
            {
                $.ajax({
                  type: "GET",
                  url: "search.php",
                  data: {show : search, key : '890k4900k0ll' }
                }).done(function(msg){
                    $('#t').html(msg);
                });
            }
        });
    });
</script>

Search for series: <input type='text' name='tv_search' id='tv_search'>

任何想法?

推荐答案

您可以只使用一个超时和明确的每次关键是pressed:

You could just use a timeout, and clear everytime a key is pressed :

$(document).ready(function() {
    $('#tv_search').on('keyup', function() {
        clearTimeout($(this).data('timer'));
        var search = this.value;
        if (search.length >= 3) {
            $(this).data('timer', setTimeout(function() {
                $.ajax({
                    type: "GET",
                    url: "search.php",
                    data: {
                        show: search,
                        key: '890k4900k0ll'
                    }
                }).done(function(msg) {
                    $('#t').html(msg);
                });
            }, 1000);
        }
    });
});​

这篇关于执行Ajax搜索多的keydown事件一秒钟后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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