简体   繁体   中英

Autocomplete suggestion not working for ajax

I have used bootstrap typeahead for autocomplete feature.

Following code is working perfect:

$(function () {
var $input = $(".typeahead");
$input.typeahead({
    source: [
       {id: "someId1", name: "Display name 1"},
       {id: "someId2", name: "Display name 2"}
    ],
    minLength: 2
});
});

But I want to use ajax search. So I have done changes as below:

$(function () {
var $input = $(".typeahead");
$input.typeahead({
    source: function(query, process) {
        return $.get('/search/good/auto-complete?term='+$('#search_searchtext').val());
    },
    minLength: 2
});
});

Above code executes ajax request but it does not show the suggestion from ajax response.

So please suggest me how can I do that.

Try

$(function () {
    var $input = $(".typeahead");
    $input.typeahead({
        source: function(query, process) {
            return $.getJSON(
                '/search/good/auto-complete?term='+$('#search_searchtext').val(),
                //{ query: query }, // <- Maybe you can use it instead of ?term='+$('#search_searchtext').val()
                function (data) {
                    var newData = [];

                    $.each(data, function(){
                        newData.push(this.name);
                    });

                    process(newData);

                    return;
                });
        },
        minLength: 2
    });
});

for typeahead plugin i think you will need to configure the bloodhound engine. Please refer the documentation -

https://github.com/twitter/typeahead.js/blob/master/doc/jquery_typeahead.md

it should be something like this -

 var data= new Bloodhound({
    datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    remote: {
        url: '/api/data?query=%QUERY',
        wildcard: '%QUERY'
    }
});

and then you can give the source as the above data object as below -

$('#input').typeahead({
    hint: true,
    highlight: true,
    valueKey: 'name',
    minLength: 1
}, {
    name: 'title',
    display: 'name',

    source: data
});

you can give it a try.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM