【发布时间】:2016-01-11 04:50:46
【问题描述】:
这是我使用的 JSON 的一小部分(具有相同的结构)..所以我需要从 GOD 和 LEG 获取所有船名并在 JQuery 自动完成中使用它们
{
"GOD": {
"name": "This is a test",
"code": "GOD",
"ships": [
{
"layout": "normal",
"type": "Destroyer",
"name": "Ship George"
},
{
"layout": "normal",
"type": "Airship",
"name": "The strong one"
}
]
},
"LEG": {
"name": "Limited God",
"code": "LEG",
"ships": [
{
"layout": "normal",
"type": "bad",
"name": "Blair witch"
},
{
"layout": "normal",
"type": "the worst",
"name": "New era"
}
]
}
}
问题是我只想在自动完成中显示“船舶”名称。 我用于自动完成的代码是:
$("#autocomplete").autocomplete({
source: function (request, response) {
$.ajax({
dataType: "json",
data: {
term: request.term,
},
type: 'Get',
contentType: 'application/json; charset=utf-8',
xhrFields: {
withCredentials: true
},
crossDomain: true,
cache: true,
url: 'all.json',
success: function (data) {
var array = $.map(data, function (set) {
return {
label: set.name,
value: set.name
}
});
//call the filter here
response($.ui.autocomplete.filter(array, request.term));
},
error: function (data) {
}
});
},
minLength: 2,
open: function () { },
close: function () { },
focus: function (event, ui) { },
select: function (event, ui) {
$( "#card" ).val( ui.item.label );
//$( "#description" ).html( ui.item.text );
$( "#multiverseid" ).val( ui.item.multi );
$( "#project-icon" ).attr( "src", "http://gatherer.wizards.com/Handlers/Image.ashx?multiverseid=" + ui.item.multi + "&type=card" );
}
});
使用上面的代码,我可以自动完成以下值:GOD 和 LEG
如果我将行改为:
var array = $.map(data.GOD.ships, function (set) {
然后我得到所有上帝的船
我需要的是获得包含 GOD 和 LEG(以及其他“GODS”和“LEGS”)的所有船名的自动完成建议
【问题讨论】:
-
只是一个想法,如果你把 data.GOD.ships 然后放在同一个数组 data.LEG.ships 中,那么数组将填充两个值......
-
这个想法还不错,但是我将如何在 JQuery 自动完成中实现它,使用 $.map 或其他函数......
-
request.term 有什么价值?
-
这是文本字段中的值(用户输入时,自动完成功能)...
-
我放的代码只是为了让你知道我在想什么,它没有经过测试你可以试试。我会删除它作为答案。但我相信会有更好的方法。
标签: jquery json autocomplete