【发布时间】:2019-08-02 23:22:59
【问题描述】:
我正在尝试获取一个名为数量的属性的值,该属性包含在名为 items 的 JSON 数组中,但我在 jQuery 开始时不断收到“未捕获的类型错误:无法读取未定义的属性‘长度’” .each() 循环。有人可以解释我哪里出错了。非常感谢!
JSON -
{"items":[
{"id":"12345", "quantity":"2",},
{"id":"54321", "quantity":"3",}
]}
AJAX -
$(":input").bind('keyup mouseup', function () {
var self = this;
$.ajax({
url: "https://example.com/cart/change.json",
dataType: "jsonp",
data: {
id: $(this).attr('id'),
quantity : $(this).val()
},
//JSON response
success: function(data) {
console.log(data); //formatted JSON data
$('#subtotal').html(data.items_subtotal_price); //set subtotal from JSON
console.log($(self).attr('id')); //item id of clicked input
$.each(data.items.quantity, function(key,val){
console.log(key + '-' + val)
}
)}
});
});
【问题讨论】:
-
data.items是一个数组。data.items.quantity不是有效的访问器。您必须遍历项目 -
我看不出哪里出错了,谢谢 Taplar!
-
@BobtheBuilder 喜欢 Taplar 说数量不是有效的访问者检查 William Gunawan 回答以访问您的数量项目
-
是的,Williams 的解决方案很到位,谢谢!
标签: javascript jquery ajax