Typeahead.js具有远程数据源

时间:2014-08-23 22:23:05

标签: javascript jquery typeahead.js typeahead twitter-typeahead

我有一个输出

的json文件
{"data": ["A", "B", "C", "D", ...]}

我的typeahead.js脚本看起来像

var engine = new Bloodhound({
    datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    prefetch: {
        url: 'list.json',
        filter: function(list) {
            return $.map(list, function(person) { return { name: person }; });
        }
    }
});

engine.initialize();

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

正确激活了typeahead.js脚本,但它将数据源解释为只有一个逗号分隔的项而不是单独的项。因此,而不是搜索'通过元素" A"," B"," C"它只给了我一个建议" A,B,C,......"。

我的剧本出了什么问题?我已经按照http://twitter.github.io/typeahead.js/examples/上的示例进行了操作。

如果我改变了#34;名称"到"价值"在datumTokenizer,filter和displayKey中,它根本不会获得任何项目,但只输出" undefined"。我很确定它是prefetch中的过滤器选项,它无法正常工作。

1 个答案:

答案 0 :(得分:0)

在过滤器函数中,您将迭代对象的属性:

{"data": ["A", "B", "C", "D", ...]}

在这种情况下,你正在迭代"数据"只要。 要迭代"数据"中的项目,您应该通过 list.data 到过滤功能。这样:

var engine = new Bloodhound({
    datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    prefetch: {
        url: 'list.json',
        filter: function(list) {
            return $.map(list.data, function(person) { return { name: person }; });
        }
    }
});