Efficient AutoSuggest with jQuery?

别说谁变了你拦得住时间么 提交于 2019-12-02 19:50:09

Try using Ben Alman's Throttle & Debounce plugin

Lets you "delay" things till the user is done.

For an example on how to use it check out his example of debouncing with a pretend autocomplete

Your code would basically become

var qinput = $('#q').bind('keyup', $.debounce( 250, function() {

    if( $(this).val().length == 0) {
        // Hide the q-suggestions box
        $('#q-suggestions').fadeOut();
    } else {
        // Show the AJAX Spinner
        qinput.addClass('loading');

        $.ajax({
            url: '/search/spotlight/',
            data: {"q": $(this).val()},
            success: function(data) {
                $('#q-suggestions')
                    .fadeIn() // Show the q-suggestions box
                    .html(data); // Fill the q-suggestions box

                // Hide the AJAX Spinner
               qinput.removeClass('loading').addClass('search');
            }
        });
    }
}));

CSS

.loading{
    background: url('/images/ajax-loader.gif');
}
.search{
    background: url('/images/icon-search.gif');
}

You will note that I removed your background-image css and replaced them with addClass/removeClass. Much easier to manage css stuff in css files.

I'd go for a variant of C. Don't wait for users to stop typing, but wait some time (200ms?) after the first keystroke. Then after that time, you will in many cases have received additional keystrokes and then you use the typed characters to get the autosuggest. If another key is pressed after submitting the request, you start counting again.

And you should definitely do some caching too; people will use backspace and you'll have to show the name list again.

I don't know, what DB are you using OR are you using hardcoded file!?

anyway a good starting point is wait for a least a TOT NUMS of chars for

es.: after 3 ( that is a min word lenght for search mysql in most cases ) chars then you can start to search your DB or json file!

I think you must give to PHP or others the hard job like FILTERING etc, etc.. before send back the responce!

btw i think one of the best AutoSuggest is the one from brandspankingnew

The autocomplete plugin has a timeout option you can set to do this.

http://docs.jquery.com/Plugins/AutoComplete/autocomplete

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!