2

我想限制我编写的以下 ajax 实时搜索功能。

我这样做是为了仅在输入至少 2 个字符时才发送请求。我还想限制 ajax 四分之一秒,让用户有机会输入他们想要的内容。我将 ajax 包装在 setTimeout 函数中,但这不起作用。

        $('#search').keyup(function() {
            var string = $(this).val();
            if (string.length >= 2) {
                $.ajax({
                    'type': 'GET',
                    dataType: 'html',
                    'url': url,
                    'success': function(data){
                                    // show the search data
                    }
                });                                             
            } else if (string.length <= 1) {
                        // restore page content as of when it was loaded
            }
        });

我应该问的另一件事,我可能应该缓存 ajax 的结果,不是吗?

4

2 回答 2

1

查看(或考虑使用)Jquery Autocomplete的源代码它几乎完全符合您的要求,它只在暂停后提交数据以确保用户完成并且它具有缓存以及其他功能。

于 2011-08-06T03:17:07.303 回答
1

只是里面的代码if (string.length >= 2)

var elem = $(this);
// save newest search
elem.data('search',search)
// clear pending searches
.clearQueue().stop()
// waits
.delay(250)
// runs search
.queue(function() {
    $.ajax({
        'type': 'GET',
        dataType: 'html',
        'url': url,
        'success': function(data){

        // check if can be run
        if(elem.data('search') != search)
            return;

                // show the search data
        }
    });
});
于 2011-08-06T03:20:59.130 回答