简体   繁体   中英

HTML page is not showing the info I need from json file

My script, this should be showing the Name of game computers in html but it does not, I have been trying so much andI betit will just be something stupid that is wrong or missing Console says: TypeError: data is undefined

The console does show me retrieving the data works

"use strict";

window.addEventListener("load", Init);

function Init() {
  fetch("https://howest-gp-wfa.github.io/st-2021-1-S2-a-wfa-pe03-Jonas-Bundervoet/api/products.json")
  .then(function(response) { return response.json();  })
  .then(data => console.log(data))
  .then(function(data){
    tester(data)
  })
  .catch(err => console.log(err));

 window.addEventListener("load", tester);
}

My function to show data on screen (shows nothing)

function tester(data)
{
  let div = document.getElementById("test");

  for (var i = 0; i < data.length; i++) {
    let article = document.createElement("h1");
    article.innerHTML = 'Name: ' + data.GameComputers[0].Name;
    div.appendChild(article);
  };
}

In HTML I just have this in my body
<div id="test"></div>

console.log returns undefined

.then(data => console.log(data)).then(function(data){ tester(data)

Your first then returns the return value of console.log which is undefined .

So your second then recieves undefined as its data .

Don't use multiple then callbacks here.

 .then(function(data){
           console.log(data)
           tester(data)

The JSON doesn't consist of an array

The JSON you are looking at returns an object.

It doesn't have a length .

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

… is going to fail immediately.

You've got data.GameComputers[0] so I'm guessing you want to loop over GameComputers so:

  1. Check the length of that: i < data.GameComputers.length
  2. Make use of i when you read it: data.GameComputers[i].Name;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM