我有一个从我的 c# 代码返回的 json 对象。我正在循环浏览 jquery 中的结果。
一切正常,但这只是一个示例对象。实际对象要大得多,我使用的当前方法不是很干净。任何人都可以帮助我如何遍历对象内部的对象。
这是我的代码..
响应 JSON
[
{
"ProductId":7363,
"ProductName":"Brisk Waterproof Men\u0027s Jacket",
"ProductDetails":{
"ImagePath":"/assets/productimages/017/017271_BLA_MENS_BRISK_JACKET_-(10).jpg",
"ImageAltText":"BLACK:3",
"ProductSummary":"Waterproof & taped seams\r\nHighly breathable fabric\r\nDouble storm flap\r\nMultiple pockets",
"MSRP":{
100.00
},
"Price":{
65.00
}
},
"StatusCode":"Success",
"ErrorMessage":null
},
{
"ProductId":6941,
"ProductName":"Fizz Kid\u0027s Waterproof Jacket",
"ProductDetails":{
"ImagePath":"/assets/productimages/016/016792_BLA_FIZZ_KIDS_JACKET_SS13_4.jpg",
"ImageAltText":"BLACK:5",
"ProductSummary":"Waterproof & taped seams\r\nDetachable hood\r\nAdjustable hem\r\nMultiple pockets",
"MSRP":{
150.00
},
"Price":{
129.00
}
},
"StatusCode":"Success",
"ErrorMessage":null
}
]
jQuery
$('.btnGo').on("click", function (e) {
console.log("click event fired");
var jsonData = [{
ProductId: "7363"
}, {
ProductId: "6941"
}];
$.ajax({
url: "/JsonHelper/ProductHelper.ashx",
data: JSON.stringify(jsonData),
dataType: 'json',
type: 'POST',
contentType: 'application/json',
success: function (data) {
$.each(data, function (key, value) {
console.log('Object: ' + key);
var details = value.ProductDetails;
var MSRP = value.ProductDetails.MSRP;
var price = value.ProductDetails.Price;
console.log(details);
console.log(MSRP);
console.log(price);
$('.resultJson').append("<br />");
$.each(value, function (k, v) {
$('.resultJson').append(k + ": " + v + "<br />");
if (k == "ProductDetails") {
if (details != null) {
$.each(details, function (dk, dv) {
$('.resultJson').append(dk + ": " + dv + "<br />");
});
}
}
if (k == "MSRP") {
if (MSRP != null) {
$.each(MSRP, function (mk, mv) {
$('.resultJson').append(mk + ": " + mv + "<br />");
});
}
}
if (k == "Price") {
if (price != null) {
$.each(price, function (pk, pv) {
$('.resultJson').append(pk + ": " + pv + "<br />");
});
}
}
});
$('.resultJson').append("---------------- ------------------");
});
},
error: function (data, status) {
console.log("FAILED:" + status);
}
});
});
我对 $.each 很困惑,不知道如何有效地循环多个对象。