提取未定义的API数据

时间:2019-06-24 09:14:07

标签: json fetch-api

我一直在尝试获取和显示数据,但是一直没有显示,当我在控制台上查看时,它显示“ TypeError:“ data.collections未定义”“,我一直在努力理解原因。寻求帮助,以便显示文字会很棒。

这是我的代码:

我的JSON文件:

[
  {
    "archives": {
      "year1": {
        "title": "Sample Title 1"
      },
      "year2": { 
        "title": "Sample Title 2"
      },
      "year3": {
        "title": "Sample Title 3"
      }
    },    
    "collections": {
      "health": {
        "title": "Sample Title 4"
      },
      "money": { 
        "title": "Sample Title 5"
      },
        "relationships": {
      "title": "Sample Title 6"
      }
    }
  } 
] 

HTML:

        <div class="archives"></div>
        <div class="collections"></div>

JavaScript:

        fetch('final.json')
        .then(function (response) {
            return response.json();
        })
        .then(function (data) {
            appendData(data);
        })
        .catch(error => console.log('Looks like there was a problem: ', error));

        function appendData(data) {
            var mainContainer = document.getElementById("archives");
                for (var i = 0; i < data.archives.length; i++) {
                    var div = document.createElement("div");
                        div.innerHTML = 
                        '<span class="archives">' + 
                         data[i].archives.year1.title + '</span>' + 
                        '<span class="archives">' + 
                         data[i].archives.year2.title + '</span>' +
                        '<span class="archives">' + 
                         data[i].archives.year3.title + '</span>';
                     mainContainer.appendChild(div);
                }
            }

            function appendData(data) {
                var mainContainer = document.getElementById("collections");
                    for (var i = 0; i < data.collections.length; i++) {
                        var div = document.createElement("div");
                            div.innerHTML = 
                            '<span class="collections">' + data[i].collections.health.title + '</span>' + 
                            '<span class="collections">' + data[i].collections.money.title + '</span>' +
                            '<span class="collections">' + data[i].collections.relationships.title + '</span>';
                        mainContainer.appendChild(div);
                    }
                }

在控制台中,错误中显示的两行代码是:

 appendData(data);

 for (var i = 0; i < data.collections.length; i++) {

它也说:

 "TypeError: Unable to get property 'length' of undefined or null reference"

1 个答案:

答案 0 :(得分:0)

您的JSON data是一个数组,因此访问器data.archivesdata.collections实际上并不存在。这意味着您正在尝试调用undefined.length,这是您的错误出处。您需要将访问者设置为data[0].archivesdata[0].collections