Twitter Typeahead.js Bloodhound远程返回undefined

aly*_*yus 4 jquery undefined typeahead.js twitter-typeahead bloodhound

无法获得Twitter Typeahead.js,远程版本可以使用.我的建议得到"未定义".任何帮助,将不胜感激.

代码如下:

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()
});
Run Code Online (Sandbox Code Playgroud)

Ben*_*ith 5

Bloodhound建议引擎无法在JSON数组中找到显示键"value".

您需要将JSON数组转换为JavaScript对象数组.JavaScript对象有一个名为"value"的变量,它有一个电影标题作为其值; 这是显示键使用的"值"变量,例如

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
                };
            });
        }
    }
Run Code Online (Sandbox Code Playgroud)

如果你包含了films.json输出的样本,那么上面的例子可以得到改进(因为我可以使用你需要的确切值).

有关扩展示例和jsfiddle,请参阅答案.