我有一个名为names.json的json,我需要使用autocomplete进行输入,在json中查找“name”值。
我该怎么做?
我试过:
$(function () {
var getData = function (request, response) {
$.getJSON(
"/cities.json" + request.term,
function (data) {
response(data);
});
};
var selectItem = function (event, ui) {
$("#myInput").val(ui.item.value);
return false;
}
$("#myInput").autocomplete({
source: getData,
select: selectItem,
minLength: 2,
change: function() {
$("#myInput").val("").css("display", 2);
}
});
});
但我在代码中做错了。
我从外部文件中获取了json
JSON完全来自这种格式,当我输入输入时,我需要返回'names'的值:
[
{
"id":25,
"name":"locale name test 2",
"state_id":6
},
{
"id":667,
"name":"locale name test 3",
"state_id":24
},
{
"id":331,
"name":"locale name test 4",
"state_id":13
},
{
"id":776,
"name":"locale name test 5",
"state_id":26
},
{
"id":680,
"name":"locale name test 6",
"state_id":26
}
]
答案 0 :(得分:2)
这是基于您提供的数据的基本工作自动完成示例。
HTML:
<input type="text" id="suggestion" />
Jquery的:
var data = [
{
"id":25,
"name":"locale name test 2",
"state_id":6
},
{
"id":667,
"name":"locale name test 3",
"state_id":24
},
{
"id":331,
"name":"locale name test 4",
"state_id":13
},
{
"id":776,
"name":"locale name test 5",
"state_id":26
},
{
"id":680,
"name":"locale name test 6",
"state_id":26
}
]
var data_arr = data.map(function(val){
return val.name;
}). //get all the val.names on an array to make
// it easier when it comes setting autocomplete source
console.log(data_arr)
$("#suggestion").autocomplete({
source: data_arr,
minLength: 2
});
以下是jsFiddle
上托管的上述代码的工作版本另外: 如果你必须从外部来源获取数据,我就是这样做的
HTML:
<input type="text" id="suggestion" />
Jquery的:
// I have hosted the same data you provided on myjson.com
$.getJSON( "https://api.myjson.com/bins/1gkh25", function( data ) {
var data_arr = data.map(function(val){
return val.name;
})
auto(data_arr)
});
function auto(data_arr){
$("#suggestion").autocomplete({
source: data_arr,
minLength: 2
});
}
上试试