引导程序提前返回名称和ID [英] bootstrap typeahead return name and id
问题描述
嗨!我正在使用Twitter Bootstraps提前输入:
Hy! I'm using twitter bootstraps typeahead:
我正在调用一个返回带有json_encode响应的页面 该页面返回名称和ID,
I'm calling a page that returns a response with json_encode the page returns a name and an ID,
我希望预先输入列表可以显示姓名列表, 当我选择一个名字 将id值写入隐藏字段.
I want that the typeahead list will show me the list of names, and when I select one of the name to write the id value to a hidden field.
调用工作正常,并且编写字段应该很容易. 我不知道该怎么做是如何将名称与ID分开.
the calling works fine, and to write a field should be easy. what i dont know what to do is how to divide the name from the id.
现在,当我搜索某些东西时,在建议列表中,我可以看到如下返回结果:
now, when i search something, in the suggesstion list I can see the returning results like this:
name1:id1 name2:id2
name1:id1 name2:id2
我只想看名字,但也要携带id的值.
i only want to see names but to carry the value of id too.
我该怎么做?
$(function(){
$("#typeahead_<? print $key; ?>").typeahead(
{
source: function(query, process)
{
$.ajax({
url: '/getAjaxProducts',
type: 'POST',
data: 'query=' + query,
dataType: 'JSON',
async: true,
success: function(data)
{
process(data);
}
});
}
});
});
推荐答案
一个包含名称/ID对的典型JSON文档将如下所示:
A typical JSON document that contains name/ID pairs is going to look like this:
[
{
"id": 1
"name": "firstName"
},
{
"id": 2
"name": "secondName"
}
]
这里的策略是构建一个对象文字,在解析结果时将名称映射到ID,同时仅使用名称填充预输入:
The strategy here is to build an object literal that maps names to IDs as you parse the result, while only using the name to populate the typeahead:
var productNames = new Array();
var productIds = new Object();
$.getJSON( '/getAjaxProducts', null,
function ( jsonData )
{
$.each( jsonData, function ( index, product )
{
productNames.push( product.name );
productIds[product.name] = product.id;
} );
$( '#product' ).typeahead( { source:productNames } );
} );
一旦用户从预输入中选择了一个项目,您可以通过以下方式引用选定的项目:
Once the user selects an item from the typeahead, you can reference the selected item with:
$( '#product' ).val()
,您可以通过以下方式获取与所选项目关联的ID:
and you can get the ID associated with the selected item with:
productIds[$( '#product' ).val()]
从您的问题来看,您的JSON文档的结构似乎有些不同,因此您可以适当地更改解析,但适用相同的常规策略.
From your question, it looks like your JSON document may be structured a little bit differently, so you would change the parsing as appropriate, but the same general strategy applies.
这篇关于引导程序提前返回名称和ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!