我有国家的json列表:http://vocab.nic.in/rest.php/country/json
我试图通过Bloodhound建议引擎获取country_id和国家/地区名称。我尝试了以下代码:
var countries = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('country_name'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
limit: 10,
prefetch: {
url: 'http://vocab.nic.in/rest.php/country/json',
filter: function(response) {
return response.countries;
}
}
});
$('#my-input').typeahead({
hint: true,
highlight: true,
minLength: 1
},
{
name: 'states',
displayKey: 'value',
source: countries.ttAdapter()
});
哪个不起作用。我该如何更改代码才能使其正常工作?
答案 0 :(得分:13)
// instantiate the bloodhound suggestion engine
var countries = new Bloodhound({
datumTokenizer: function(countries) {
return Bloodhound.tokenizers.whitespace(countries.value);
},
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: {
url: "http://vocab.nic.in/rest.php/country/json",
filter: function(response) {
return response.countries;
}
}
});
// initialize the bloodhound suggestion engine
countries.initialize();
// instantiate the typeahead UI
$('.typeahead').typeahead(
{ hint: true,
highlight: true,
minLength: 1
},
{
name: 'countries',
displayKey: function(countries) {
return countries.country.country_name;
},
source: countries.ttAdapter()
});
<强> Example Codepen 强>
预先输出
注意:
答案 1 :(得分:0)
注意:如果您执行了所有这些操作,但仍然无法正常工作,请检查您的data.json文件(无论您如何命名)
格式良好的示例: https://github.com/twitter/typeahead.js/blob/gh-pages/data/countries.json
['data1','data2',.....]
我被绊倒了。