我正在尝试预取整个 JSON 数据库 (55kb),以便将其与 typeahead.js 0.11.1 一起使用。我一整天都在为此苦苦挣扎,我发现 typeahead.js 文档在这方面非常基础。
我的 JSON 看起来像这样:
[{
"id": 1,
"name": "Green"
}, {
"id": 2,
"name": "Red"
}, {
"id": 3,
"name": "Blue"
}]
和 JavaScript:
$(function() {
var tagSuggestion = new Bloodhound({
datumTokenizer: function(d) {
return Bloodhound.tokenizers.whitespace(d.name);
},
queryTokenizer: Bloodhound.tokenizers.whitespace,
limit: 10,
prefetch: {
url: 'ajax.json-colors.php'
}
});
$('.typeahead').typeahead({
hint: true,
highlight: true,
minLength: 2
}, {
name: 'tagSuggestion',
displayKey: 'name',
source: tagSuggestion.ttAdapter()
});
});
我不知道我做错了什么,但是 typeahead 不能与预取一起使用。
最佳答案
也许类似这样的东西可能会起作用:
var tagSuggestion = new Bloodhound({
datumTokenizer: function(d) {
return Bloodhound.tokenizers.whitespace(d.name);
},
queryTokenizer: Bloodhound.tokenizers.whitespace,
limit: 10,
prefetch: {
url: 'ajax.json-colors.php',
filter: function (data) {
//console.log(data.response) --> see if this is your data in example above
return $.map(data.response, function (tags) {
return {
name: tags.name
};
});
}
}
});
假设预取中返回的数据采用包含数据的响应对象的形式。可能需要根据传递给过滤器的数据
进行修改。
这是如果 ajax 响应是一个键值,键为“response”。如果没有有效的 fiddle ,我只能猜测问题。
关于javascript - Twitter typeahead.js 0.11.1 预取不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39144019/