jquery自动完成json文件键值

时间:2017-08-25 04:45:37

标签: javascript jquery json autocomplete

我有一个带有JSON源文件的工作自动完成字段。现在我想将JSON更改为键值格式。喜欢这个

{"Countries":{"Andorra":"AD","United Arab Emirates":"AE"}}

如何让字段存储“AD”并自动完成“安道尔”?

$(function () {

$.get('../data/data.json', function (data) {

    var country = Object.keys(data['Countries']).map(function (k) {
        return data['Countries'][k]
    });

    $('#country_autocomplete').autocomplete({
        lookup: country,
        onSelect: function (suggestion) {
            console.log('You selected: ' + suggestion.key);
        }
    });
});

});

1 个答案:

答案 0 :(得分:0)

在这里,我已根据自动完成的需要将JSON响应转换为一个;

var data = {"Countries":{"Andorra":"AD","United Arab Emirates":"AE" , "India" : "IN" , "Australia" : "AUS"} } ;

var countries = [] ;

var country_full_names = new Array();
country_full_names =   Object.keys(data.Countries);

country_full_names.forEach( function( element  ){
    var obj = {};
    obj.value = element ;
    obj.data = data.Countries[element] ;
    console.log(obj);
    countries.push(obj);
});




$('#country_autocomplete').autocomplete({
  lookup: countries,
 onSelect: function (suggestion) {
       alert('You selected: ' + suggestion.value + ', ' + suggestion.data);
    }
});

在上面的代码片段中,我在没有AJAX / XHR的情况下初始化了数据 。但是对于init的请求只需用这个

替换第一行
var data = {};
$.get('../data/data.json', function ( response ) {
 data = response ;
 }); 

这是工作小提琴 https://jsfiddle.net/u77va6xt/