使用jQuery解析获取的JSON时出错

时间:2013-03-18 00:56:17

标签: jquery ajax json

我正在尝试使用jQuery解析JSON文件。我想在新类别中返回每个image_url(减去第一个字符)并将图像放在页面上。

这是我的代码

function redo () {
$('#init').addClass('disabled');
$.getJSON('http://server/new/sample.json', function(data) {
    $.each(data.products_and_categories.new, function(item){
      $("<img/>").attr("src", "http://d2flb1n945r21v.cloudfront.net/production/uploaded/style/" + item.image_url.substring(1)).appendTo("#items");
    });
  });
$('#init').removeClass('disabled');
};

并在chrome检查器中返回此错误

Uncaught TypeError: Cannot call method 'substring' of undefined

为什么不定义?

1 个答案:

答案 0 :(得分:5)

$.each()的回调函数的第一个参数是索引,第二个参数是值。

尝试:

$.each(data.products_and_categories.new, function(index, item){