我知道这个问题已经被问了很多次,但每次我得到未定义的变量时,我都会卡在某个地方获取数据。 有人可以帮忙使用 jquery ajax 遍历 JSON 数据吗?
[
{
"Orderdetails":[
{
"errorMsg":"success",
"customername":"Walk In Customer",
"grandtotal":"1496.00",
"outletname":"Pradhan Ji Mobile",
"paymentmethodname":"Cash",
"customer_id":"1",
"outlet_id":"13"
}
]
},
{
"product":[
{
"product_name":"Tripr Printed Men V-neck Multicolor T-Shirt",
"product_code":"5674664",
"price":"374.00",
"qty":"2"
},
{
"product_name":"Tripr Printed Men V-neck Multicolor T-Shirt",
"product_code":"5674665",
"price":"374.00",
"qty":"1"
},
{
"product_name":"Tripr Printed Men V-neck Multicolor T-Shirt",
"product_code":"5674666",
"price":"374.00",
"qty":"1"
}
]
}
]
提前谢谢。
如果你想获取customer_id的意思,试试data[0].Orderdetails[0].customer_id
其中数据将是 JSON。
你得到的对象是一个包含 2 个对象的列表,Orderdetails
和product
都包含另一个列表。如果您想摆脱Orderdetails
customer_id
,您可以按以下步骤进行操作。
// let's assume the list is called jsonList.
// Orderdetails is an element of the first list
const orderdetails = jsonList[0].Orderdetails;
// Then get the customer_id out of the first list in Orderdetails
const customer_id = Orderdetails[0].customer_id;
或者所有这些都以更短的方式进行
const customer_id = jsonList[0].Orderdetails[0].customer_id;
编辑
如果要循环访问product
请使用.forEach()
// get the list product
const product = jsonList[0].product;
// iterate through it with forEach()
product.forEach( element => {
// you now have access to the fields of each single element of the list
console.log('product_name', element.product_name);
console.log('product_code', element.product_code);
// .. and so on
});