2016-10-11 70 views
0

我在这里有一些问题,在这里jQuery。所以我想用JSON对象从数据库进行自动完成文本字段,在这里我提供我的代码jQuery autocomplate解析来自json对象的特定数据数组

的jQuery:

$('#school_name').autocomplete({ 
    minLength: 3, 
    autoFocus: true, 
    source: function(request, response) { 
      $.getJSON('https://host/path', { q: $('#school_name').val() }, 
    response); 
} 

返回JSON

{ 
    "status": "success", 
    "result": { 
    "data": [ 
     { 
     "school_id": xxx, 
     "school_name": "xxx", 
     "status": "Swasta", 
     "address": "xxx", 
     "city": "BANYUWANGI", 
     "province": "JAWA TIMUR", 
     "phone": "1234", 
     "email": "[email protected]", 
     "picture": null, 
     "is_published": "Y" 
     }, 
     { 
     "school_id": xxx, 
     "school_name": "xxx", 
     "status": "Swasta", 
     "address": " ", 
     "city": "", 
     "province": "", 
     "phone": "-", 
     "email": null, 
     "picture": null, 
     "is_published": "Y" 
     } 
    ] 
    } 
} 

我不想回值json对象就像我有,我只需要school_name在数组形式,请帮我解决我的问题

回答

1

使用response回调推你想要的数据。

$('#school_name').autocomplete({ 
    minLength: 3, 
    autoFocus: true, 
    source: function(request, response) { 

    $.get('https://host/path').always(function(res) { 

     var json = JSON.parse(res), result_arr = []; 
     $.each(json.result.data, function(k,v) { 
      result_arr.push(v.school_name); 
     }); 
     response(result_arr); 

    }); 

    } 
}); 
+1

这个为我工作谢谢^ _ ^ –

0

您可以使用Array.prototype.map来转换数组。 map将对数组中的每个项目运行一个函数,并使用返回的值创建一个新数组。

const json = { 
 
    "status": "success", 
 
    "result": { 
 
    "data": [ 
 
     { 
 
     "school_id": '1234', 
 
     "school_name": "First School Name", 
 
     "status": "Swasta", 
 
     "address": "xxx", 
 
     "city": "BANYUWANGI", 
 
     "province": "JAWA TIMUR", 
 
     "phone": "1234", 
 
     "email": "[email protected]", 
 
     "picture": null, 
 
     "is_published": "Y" 
 
     }, 
 
     { 
 
     "school_id": '5678', 
 
     "school_name": "Second School Name", 
 
     "status": "Swasta", 
 
     "address": " ", 
 
     "city": "", 
 
     "province": "", 
 
     "phone": "-", 
 
     "email": null, 
 
     "picture": null, 
 
     "is_published": "Y" 
 
     } 
 
    ] 
 
    } 
 
} 
 

 
console.log(
 
    json.result.data.map(school => school.school_name) 
 
)