【问题标题】:Twitter Typeahead.js Bloodhound remote returns undefinedTwitter Typeahead.js Bloodhound 远程返回未定义
【发布时间】:2014-09-22 23:17:06
【问题描述】:

无法让远程版本的 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()
});

【问题讨论】:

    标签: jquery undefined typeahead.js twitter-typeahead bloodhound


    【解决方案1】:

    Bloodhound 建议引擎无法在您的 JSON 数组中找到显示键“值”。

    您需要将 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
                    };
                });
            }
        }
    

    如果您包含您的films.json 输出示例,上述示例可能会得到改进(因为我可以使用您需要的确切值)。

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

    【讨论】:

    • 感谢本的帮助。回答接受。再次感谢!
    • 很高兴我能帮助@jfrosty :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-22
    • 1970-01-01
    相关资源
    最近更新 更多