我有一个 JSON 响应,我正在尝试让自动完成功能正常工作,但它有问题。
问题:
这是我的 jQuery ajax“成功”方法来处理返回的 JSON 字符串:(我在下面列出了我的 JSON 响应):
代码:
success: function( data ) {
response( $.map( data.productSkus, function( item ) {
return {
label: item.product.name + " - " + item.product.sku,
name: item.product.name,
value: item.product.sku,
id: item.product.id,
product_sku: item.product.sku
}
}));
}
问题:
我确信它不显示选项的问题是因为每个数组元素在数组内容之前都有 "0": { 。我如何访问这些?我已经尝试过 item[0] 但这似乎不起作用。我知道这个脚本是有效的,只是当我必须在我的 php 代码中执行“group by”时它就崩溃了。一旦我完成了分组,它就添加了“0”:{。感谢您的帮助!
JSON 响应:
{
"responseCode": 200,
"responseVal": "Success",
"productSkus": [
{
"0": {
"id": 16685,
"qty": 8,
"reserved_qty": 0,
"created": {
"date": "2014-01-20 17:32:31",
"timezone_type": 3,
"timezone": "Europe/Paris"
},
"updated": null,
"deletedAt": null,
"inventoryLocation": {
"id": 523,
"saleable": true,
"name": "M-10A-4",
"created": {
"date": "2013-04-11 18:46:11",
"timezone_type": 3,
"timezone": "Europe/Paris"
},
"updated": {
"date": "2013-04-11 18:46:11",
"timezone_type": 3,
"timezone": "Europe/Paris"
},
"deletedAt": null,
"warehouse": {
}
}
},
"name": "Tiger Costume Brown"
},
{
"0": {
"id": 48917,
"qty": 0,
"reserved_qty": 0,
"created": {
"date": "2014-01-20 23:44:15",
"timezone_type": 3,
"timezone": "Europe/Paris"
},
"updated": null,
"deletedAt": null,
"inventoryLocation": {
"id": 4056,
"saleable": true,
"name": "W-2E-26R-204",
"created": {
"date": "2014-01-20 23:30:58",
"timezone_type": 3,
"timezone": "Europe/Paris"
},
"updated": null,
"deletedAt": null,
"warehouse": {
}
}
},
"name": "Tiger Costume White"
}
],
"productsCount": 7
}
最佳答案
我会在 php 端仔细检查这一点,也许会纠正它(只需将元素置于零以下并直接附加它)。如果这不可能在 JS 中更正它:
success: function( data ) {
response( $.map( data.productSkus, function( item ) {
if(item[0]){
item[0].name = item.name
item = item[0];
}
return {
label: item.name + " - " + item.sku,
name: item.name,
value: item.sku, // Not in the JSON
id: item.id,
product_sku: item.sku // Not in the JSON
}
}));
}
当这不起作用时,请使用 typeof 代替。
//编辑:废话。已更正
//编辑:删除了产品 key ,因为它不存在于 JSON 中
//编辑:现在它几乎适合 json
关于javascript - jQuery AutoComplete 不适用于 JSON 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23070457/