如何使用最新的typeahead.js库呈现JSON响应 [英] How to render JSON response using latest typeahead.js library
问题描述
我的应用程序中有一个搜索框,用户可以在其中搜索存储在数据库中的患者详细信息。他们会输入患者的姓名,服务器将回复JSON响应并提供所有详细信息。为了方便这样的功能,我使用的是最新版本的typeahead.js。
I have got a search box in my application where in users can search for a patient details stored in the database. they would type in the name of the patient and server will respond back with JSON response with all the details. In order to facilitate such functionality, I am using the latest version typeahead.js.
这是我的javascript代码:
Here is my javascript code:
$("#search-box").typeahead({
remote: 'searchPatient.do?q=%QUERY'
});
此代码为我提供以下JSON响应:
This code gives me following JSON response:
[
{
"id":1,
"surname":"Daniel",
"forename":"JOHN",
"address":
{
"id":23,
"houseNameOrNumber":"35",
"addressDetail":"Roman House",
"postCode":"NE1 2JS"
},
"gender":"M",
"age":27,
"dateOfBirth":"25/08/1985"
}
]
当typeahead库尝试渲染时响应,我总是在下拉列表中看到未定义。我想在自动建议下拉列表中显示此响应的所有字段。如果有人可以指导我这样做,我将不胜感激。
When typeahead library tries to render this response, I always see undefined in the drop down list. I want to show all the fields of this response in the auto suggest drop down list. I would appreciate if someone could guide me in doing so.
我想在下拉列表中显示如下记录:
I want to display record like this in the drop down list:
John Daniel (M, 27)
35 Roman House, NE1 2JS
25/08/1985
提前致谢!
推荐答案
您当前的代码实现起来太简单了,您需要使用模板
和远程
实现:
Your current code is too simple to achieve that, you need to use template
and remote
to achieve that:
$('#search-box').typeahead([{
name: 'Search',
valueKey: 'forename',
remote: {
url: 'searchPatient.do?q=%QUERY',
filter: function (parsedResponse) {
// parsedResponse is the array returned from your backend
console.log(parsedResponse);
// do whatever processing you need here
return parsedResponse;
}
},
template: [
'<p class="name">{{forename}} {{surname}} ({{gender}} {{age}})</p>',
'<p class="dob">{{dateOfBirth}}</p>'
].join(''),
engine: Hogan // download and include http://twitter.github.io/hogan.js/
}]);
只是为了给你一个基本的想法,希望它有所帮助。
Just to give you the basic idea, hope it helps.
这篇关于如何使用最新的typeahead.js库呈现JSON响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!