使用typeahead.js从json数据中检索多个值

3
我在将远程json数据导入到 typeahead.js 时遇到了麻烦。我尝试使用预获取示例来检索注释并能够使用 typeahead.js 进行搜索,但只能获取仅包含值的简单json注释。
我使用的json数据文件是数据/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
非常感谢任何帮助。
1个回答

1

这里有一个类似的示例,您可以在此处查看:

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>")
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接