我无法将远程json数据访问到typeahead.js中。我尝试使用prefetch示例来检索笔记并能够使用typeahead.js进行搜索,但是只能获取仅包含值的简单json笔记。
我使用的json数据文件是data / notes_simple.json。
["Atomic Energy", "Introduction to Biology", ...]
搜索结果如下所示:(仅显示名称)
Electromagnetism
Introduction to Biology
我希望能够使用data / notes.json,其中包含键和值。
[{
"name": "Electromagnetism",
"subject": "Physics",
"form": "4"
}, {
"name": "Introduction to Biology",
"subject": "Biology",
"form": "1"
...
我要显示的搜索结果如下:(显示名称,主题和形式/类别)
Electromagnetism
Physics - Form 4
Introduction to Biology
Biology - Form 1
我怎样才能得到上面的东西?
我的js / prefetch.js如下所示:
$(function() {
var notes = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
limit: 10,
prefetch: {
url: 'data/notes_simple.json',
filter: function(list) {
return $.map(list, function(country) {
return {
name: country
};
});
}
}
});
notes.initialize();
$('#prefetch .typeahead').typeahead(null, {
name: 'notes',
displayKey: 'name',
source: notes.ttAdapter()
});
});
您可以在这里找到我的托管项目:http : //goo.gl/7kPVk2
任何帮助表示赞赏。
您可以在此处查看如何执行类似操作的示例:
http://jsfiddle.net/Fresh/u4fq85bj/
您需要将远程调用更改为notes.json,并适当地修改过滤器,例如
remote: {
url: '/notes.json',
filter: function (notes) {
return $.map(notes, function (note) {
return {
name: note.name,
subject: note.subject,
form: note.form
};
});
}
}
要以所需的格式显示结果,可以使用带有标记的Handlebars模板引擎,如下所示:
templates: {
suggestion:
Handlebars.compile("<p>{{name}}</p><p>{{subject}} - Form {{form}}</i></p>")
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句