我正在尝试使用Jquery Typeahead从json文件创建自动完成搜索字段,以便根据此示例在搜索输入上进行类似于Google搜索的自动完成预览:http://www.runningcoder.org/jquerytypeahead/demo/(Beer v1)。< / p>
HTML
<form>
<div class="typeahead__container">
<div class="typeahead__field">
<span class="typeahead__query">
<input class="js-typeahead-input"
name="q"
type="search"
autofocus
autocomplete="off">
</span>
</div>
</div>
</form>
JAVASCRIPT
var data = {
countries: ["Afghanistan", "Albania", "Algeria"],
capitals: ["Abu Dhabi", "Abuja", "Accra"]
};
typeof $.typeahead === 'function' && $.typeahead({
input: ".js-typeahead-input",
minLength: 1,
order: "asc",
group: true,
maxItemPerGroup: 5,
groupOrder: function () {
var scope = this,
sortGroup = [];
for (var i in this.result) {
sortGroup.push({
group: i,
length: this.result[i].length
});
}
sortGroup.sort(
scope.helper.sort(
["length"],
true, // false = desc, the most results on top
function (a) {
return a.toString().toUpperCase()
}
)
);
return $.map(sortGroup, function (val, i) {
return val.group
});
},
hint: true,
dropdownFilter: "All",
template: "{{display}}, <small><em>{{group}}</em></small>",
emptyTemplate: "nothing for : {{query}}",
source: {
country: {
data: data.countries
},
capital: {
data: data.capitals
}
},
debug: true
});
我试图通过
替换实际来源 source: {
"coutries": {
ajax: {
url: "coutries.json",
path: "data"
}
},
"capitals": {
ajax: {
url: "capitals.json",
path: "data"
}
},
}
问题是我无法添加JSON文件来加载来自。
的结果答案 0 :(得分:0)
您可以使用ajax-GET方法从数据库或您想要的其他地方获取数据。 请参阅以下脚本:
$(document).ready(function(){
$.ajax({
type: "GET",
url: "your ajax url",
dataType: "json",
success: function(data) {
typeof $.typeahead === 'function' && $.typeahead({
input: ".js-typeahead-input",
minLength: 1, //minimum character length
order: "asc",
hint: true,
source: data,
debug: true
});
}
});