0

我在名为 json/img_desc.json 的文件夹中有一个 json 文件

这是json文件

{ "theimages":[
  {
    "number":1,
    "title":"Joy Toy teddy bear",
    "description":"In etc etc"
  } etc etc

然后我使用此代码尝试获取第一个值。

 $.getJSON('json/img_desc.json', function(theimages) {
    console.log(img_desc.theimages.number[0]);
});

错误

它说这个

[15:06:46.951] ReferenceError: img_desc 未定义@file:///[为隐私删除]/js/puzzle.js:246

4

3 回答 3

5

它应该是

$.getJSON('json/img_desc.json', function (theimages) {
    console.log(theimages.theimages[0].number);

    //if you want to loop
    $.each(theimages.theimages, function (idx, obj) {
        console.log(obj.number)
    })
});
于 2013-10-14T05:11:35.760 回答
2

文档说http://api.jquery.com/jQuery.getJSON/#jQuery-getJSON-url-data-success-data--textStatus--jqXHR-它将传递一个普通对象作为第二个参数。所以,你可以做这样的事情

$.getJSON('json/img_desc.json', function(theimages) {
    $.each(theimages.theimages, function( index, val ) {
        console.log(val, val.number);
  });
});
于 2013-10-14T05:15:06.327 回答
1
 $.getJSON('json/img_desc.json', function(img_desc) {
    console.log(img_desc.theimages.number[0]);
});

应该解决你的问题。如果您有任何其他问题,请在单独的问题中提出。

于 2013-10-14T06:10:07.743 回答