Update JSON on every keyup for twitter typeahead

后端 未结 2 1887
别那么骄傲
别那么骄傲 2020-12-06 23:23

I have a html page with an input field. Every time something is typed in this field, there is a call done to a php script with jQuery.

This php script returns a JSON

2条回答
  •  借酒劲吻你
    2020-12-06 23:46

    What I ended up doing is to use Bloodhound and, specifically, replace to create an appropriate query:

    var states = new Bloodhound({
        ...
        remote: {
                url: 'suggest.php?input=',
                replace: function (url, query) {
                        suggestion.input = query;
                        return url + suggestion.input;
                },
                ...
        }
    });
    states.initialize();
    

    All together, the full code looks like this:

    $(function(){
    
            var suggestion = {
                    input: '',
                    normalized: ''
            };
            var states = new Bloodhound({
                    datumTokenizer: function (d){
    
                    },
                    queryTokenizer: Bloodhound.tokenizers.whitespace,
                    remote: {
                            url: 'get_names.php?input=',
                            replace: function (url, query) {
                                    suggestion.input = query;
                                    return url + suggestion.input;
                            },
                            filter: function (data) {
                                    return $.map(data, function(company) { return { value: company }; });
                                    }
                    }
            });
            states.initialize();
    
            $('#the-basics .typeahead').typeahead({
                    minLength: 1,
                    highlight: true
                    },{
                    displayKey: 'value',
                    source: states.ttAdapter()
            });
    });
    

提交回复
热议问题