Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

108
Visualizações
Is there a solution?

So, i'm trying to run this code to put the information from the JSON file to the HTML page. This is the code im trying to run:

HTML:

<div id="gameContainer">
        <script>
        var games = "../games.json"
      
      document.getElementById("gameContainer").innerHTML = `<h1>${games.author}</h1>`
    </script>
</div>

games.json:

[
  {
      "name": "gameName",
      "author": "authorName"
  }
]

On the site, the html says "undefined" and that's it. No errors in the console, nothin.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You will have to fetch the file first in order to read the contents of the file.

const url = '../games.json';

const fetchJson = async () => {
    try {
        const data = await fetch(url);
        const response = await data.json();
        document.getElementById('gameContainer').innerHTML = `<h1>${response[0].author}</h1>`;
    }
    catch (error) {
        console.log(error);
    }
};

also, your games is an Array! So you need to use an Array index in order to then get the containing Object like: games[0].author, not games.author.

about 4 years ago · Juan Pablo Isaza Relatório

0

You cannot make a AJAX call to a local resource as the request is made using HTTP.

A workaround is to run a local webserver, serve up the file and make the AJAX call to localhost.

In terms of helping you write code to read JSON, you should read the documentation for jQuery.getJSON():

http://api.jquery.com/jQuery.getJSON

Here's a way to do it without jQuery.

First create this function:

function loadJSON(callback) {   
  var xobj = new XMLHttpRequest();
  xobj.overrideMimeType("application/json");
  xobj.open('GET', '../news_data.json', true);
  xobj.onreadystatechange = function () {
    if (xobj.readyState == 4 && xobj.status == "200") {
      callback(JSON.parse(xobj.responseText));
    }
  };
  xobj.send(null);  
}

Then you can use it by simply calling something like this:

loadJSON(function(json) {
  console.log(json); // this will log out the json object
});

source

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda