未捕获的类型错误:无法读取 jQuery $.each 和 JSON 中未定义的属性'length'



我正在尝试获取一个称为数量的属性的值,该属性包含在一个称为项目的JSON数组中,但我一直在获得" Unduck typeError:无法读取的属性'长度'未定义的"在jQuery.east((循环的开头。有人可以解释一下我出错的地方吗?非常感谢!

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)
          }
)}
});
});

您在这里错了。

      $.each(data.items.quantity, function(key,val){
  console.log(key + '-' + val)
      });

上面的代码您正在尝试指向数据。访问每个内部的数量。

应该像这样

$.each(data.items, function(index, item){
  console.log(item.quantity);
});

最新更新