我在这里遇到一些问题jquery。所以我想使用数据库中的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": "xx@a.co",
"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 的数组形式,请帮我解决我的问题
答案 0 :(得分: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": "xx@a.co",
"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)
)