gpt4 book ai didi

javascript - 在 AJAX 自动完成中操作 JSON

转载 作者:行者123 更新时间:2023-12-03 05:11:24 25 4
gpt4 key购买 nike

嗨,我通常是一个对 jquery 不太熟悉的后端人员,但我想创建一个简单的 UI 来使用 ajax 自动完成功能查询我的 API 服务,假设我有 JSON 返回,如下所示

{ addresses": [
{
"id": "gmap_auto3961949943bb427782ca7b3d1df6c64f",
"name": "819643",
"secondary_name": "Singapore",
"description": "Singapore 819643",
"types": [
"postal_code"
],
"attributes": {
"latitude": 1.355322,
"longitude": 103.988337
}
},
{
"id": "gmap_autoc98babeabdf77fd2788871786fed14ef",
"name": "819663",
"secondary_name": "Singapore",
"description": "Singapore 819663",
"types": [
"postal_code"
],
"attributes": {
"latitude": 1.356716,
"longitude": 103.98651
}
},
]
}

所以我的意图是将名称和次要名称作为标签,将 id 作为值。我怎么做?下面是我的 AJAX

$( function() {
function log( message ) {
$( "<div>" ).text( message ).prependTo( "#log" );
$( "#log" ).scrollTop( 0 );
}

$( "#address" ).autocomplete({
source: function( request, response ) {
$.ajax( {
url: "/address/autocomplete",
data: {
q: request.term,
countryCode: "sg"
},
success: function( data ) {
var ParsedObject = $.parseJSON(data);
response($.map(ParsedObject.addresses, function (item) {
return {
label: item.name,
value: item.secondary_name
};

}))
}
});
},

minLength: 2,
select: function( event, ui ) {
log( "Selected: " + ui.item.name + ", " + ui.item.secondary_name );
}
});
});

提前致谢

最佳答案

在您的成功回调中

success: function( data ) {
var ParsedObject = $.parseJSON(data);
response($.map(ParsedObject.addresses, function (item) {
return {
label: item.name + ":" + item.secondary_name, //any delimiter to separate name and secondary name
value: item.id //taking id from result
};
}))
}

在您的select回调中

select: function( event, ui ) { //on selection of autocomplete dropdown
console.log( "Selected: " + ui.item.label + ", " + ui.item.value); //prints Selected: name:secondary_name, id
//you can do whatever you want with label and value here
}

关于javascript - 在 AJAX 自动完成中操作 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41802783/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com