如何将复杂的嵌套json映射到jquery自动完成格式?

时间:2017-03-24 17:00:59

标签: javascript json jquery-ui-autocomplete

如何将复杂的嵌套json映射到jquery自动完成格式?我试图将我的自定义json映射到所需的jquery自动完成格式标签,值,...但我的列表是'undefined'。这是我的设置:

JSON:

{"data":[{"DT_RowId":"row_A6J851","accounts":{"code":"A6J851","name":"Peter Jackson"}},{"DT_RowId":"row_1D01Q14","accounts":{"code":"1D01Q14","name":"Earl Bundy"}}]}

使用Javascript:

$('#input-search').autocomplete({
source: function ( request, response ) {
  $.ajax({
    type: 'GET',
    url: '/source.php', 
    dataType: "json",
    success: function( data ) {
        response( $.map( data.data.accounts, function( value, key ) {
            return {
              label: value.name,
              value: value.name,
              id: value.code
            }
        }));
      }
    });
},  
create: function() {            
    $(this).data('ui-autocomplete')._renderItem  = function (ul, item) {
        return $( "<li></li>" )
            .append( "<a>" + item.label + "</a>" )
            .appendTo( ul );
    };         
}       
});

1 个答案:

答案 0 :(得分:2)

从您的数据示例看,您不是在嵌套帐户数组上进行迭代,而是在数据数组中进行迭代。尝试这样的事情:

$('#input-search').autocomplete({
  source: function ( request, response ) {
    $.ajax({
      type: 'GET',
      url: '/source.php', 
     dataType: "json",
     success: function( data ) {
       var results = [];
       $.each(data.data, function(d){
         var mapped = $.map(d.accounts, function( value, key ) {
          return {
            label: value.name,
            value: value.name,
            id: value.code
           };
          })
         results = results.concat(mapped);       
         });
         response(results);
        }
      });
 },  
 create: function() {            
    $(this).data('ui-autocomplete')._renderItem  = function (ul, item)     {
         return $( "<li>" )
            .append( "<span>" + item.label + "</span>" )
            .appendTo( ul );
  };         
 }       
});