我无法将远程 json 数据访问到 typeahead.js .我尝试使用 prefetch example检索笔记并能够使用 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" 
... 

我要出现的搜索结果如下: (显示姓名、主题和表格/类(class))

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


评论关闭
IT序号网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!