Twitter Typeahead.js Bloodhound remote returns undefined

非 Y 不嫁゛ 提交于 2019-11-30 17:41:54

问题


Having trouble getting Twitter Typeahead.js, the remote version to work. I get "undefined" for my suggestions. Any help would be appreciated.

Code below:

JS:

var films = new Bloodhound({
    datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    remote: '../widgets/films.json'
});

films.initialize();

$('#films .typeahead').typeahead(null, {
    name: 'films',
    displayKey: 'value',
    source: films.ttAdapter()
});

回答1:


The Bloodhound suggestion engine is unable to find the display key "value" within your JSON array.

You need to convert the JSON array into an array of JavaScript objects. The JavaScript objects have a variable called "value", which have a film title as its value; it is this "value" variable which is used by the display key e.g.

remote: {
        url: '../widgets/films.json',
        filter: function (films) {
            // $.map converts the JSON array into a JavaScript array
            return $.map(films.results, function (film) {
                return {
                    // NB : replace original_title below with your JSON film key
                    value: film.original_title
                };
            });
        }
    }

The example above could be improved if you included a sample of your films.json output (as I'd then be able to use the exact values you need).

See this answer for an extended example and jsfiddle.



来源:https://stackoverflow.com/questions/25984508/twitter-typeahead-js-bloodhound-remote-returns-undefined

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