JSON 变量未定义

json variable is undefined

本文关键字:未定义 变量 JSON      更新时间:2023-09-26

我在一个名为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] 引用错误:未定义img_desc @ file:///[出于隐私原因删除]/js/puzzle.js:246

应该是

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

文档说 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);
  });
});
 $.getJSON('json/img_desc.json', function(img_desc) {
    console.log(img_desc.theimages.number[0]);
});

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