[英]I think I'm being stupid… but I can't get my JSON output properly
我正在尝试建立一个购物车。
有一个非常简单的类,它创建了一个generic.dictionary(of string, generic.dictionary(of string, string)
它包含我的购物车项目。
初始字典的键是项目ID,因此我可以使用cartDictionary.ContainsKey(id)
轻松检查项目是否已经在购物车中,然后根据需要增加数量或添加新项目。
BUY按钮触发和AJAX-ified web方法,它返回如下所示的数据:
{
"d": {
"7907": {
"id": "7907",
"qty": "4",
"singlePrice": "1185"
},
"2698": {
"id": "2698",
"qty": "1",
"singlePrice": "1322"
}
}
}
由于我不理解的原因,最初的项目d
由AJAX帖子自动创建,但它并不重要,因此我的输出在我的AJAX成功中是data.d
,如下所示:
success: function (data) {
result = [data.d];
}
现在,由此我需要能够获取内部数据以将其呈现到购物车中
所以我需要能够通过ID循环遍历项目并提取
id
qty
singlePrice
这样我就可以在浏览器中显示它了,但是我正在试图解决这个问题。
我试过添加[
围绕data.d,像
var result = [data.d]
并尝试在结果中循环,如
result = [data.d];
$(result).each(function (i, thing) {
var thisOne = (result[i]);
//alert(thing); //<< returns object object
$(thisOne).each(function (j, val) {
alert(thisOne + " - " + val.id); //<< both thisOne and val.id return object object
});
});
通过警报的返回我正在清除获取某种JSON对象,但我显然已经混淆了一些东西!
我不是程序员,但正在做一个慢慢让我疯狂的项目!
success: function (data) {
var d = $.parseJSON(data.d);
for(var i =0;i<d.length;i++)
{
alert("Id is"+d[i].id);
}
}
你应该做
var data = {
"d": {
"7907": {
"id": "7907",
"qty": "4",
"singlePrice": "1185"
},
"2698": {
"id": "2698",
"qty": "1",
"singlePrice": "1322"
}
}
}
var result = data.d;
$.each(result , function(ind, el) {
//alert(thing); //<< returns object object
alert(ind + " - " + el.id);
});
你需要使用jQuery的泛型迭代器$.each()
而不是它的jQuery对象迭代器$().each()
:
success: function (data) {
$.each(data.d, function(k, val) {
// "val" is the current item, so use its properties here, e.g.:
var id = val.id,
total = +val.qty * +val.singlePrice;
});
}
(简单演示: http : //jsfiddle.net/2vvfZ/ )
请注意,当迭代对象的属性时,订单无法保证(当我在Chrome中测试它时,它会执行2698项目,然后是7907项目)。 如果您需要确定订单使用对象数组。
你可以使用for..in循环:
for (key in data.d)
{
document.write(key + '<br>')
document.write('<blockquote>')
document.write('id: ' + data.d[key].id + '<br>')
document.write('qty: ' + data.d[key].qty + '<br>')
document.write('singlePrice: ' + data.d[key].singlePrice + '<br>')
document.write('</blockquote>')
}
结果:
2698
id: 2698
qty: 1
singlePrice: 1322
7907
id: 7907
qty: 4
singlePrice: 1185
JSFiddle: http : //jsfiddle.net/qnqWK/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.