Entonces, estoy tratando de ejecutar este código para poner la información del archivo JSON en la página HTML. Este es el código que estoy tratando de ejecutar:
HTML:
<div id="gameContainer"> <script> var games = "../games.json" document.getElementById("gameContainer").innerHTML = `<h1>${games.author}</h1>` </script> </div>juegos.json:
[ { "name": "gameName", "author": "authorName" } ]En el sitio, el html dice "indefinido" y eso es todo. No hay errores en la consola, nada.
Primero tendrá que buscar el archivo para leer el contenido del archivo.
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); } }; Además, ¡tus games son una matriz! Por lo tanto, debe usar un índice de matriz para luego obtener el objeto contenedor como: games[0].author , no games.author .
No puede realizar una llamada AJAX a un recurso local ya que la solicitud se realiza mediante HTTP.
Una solución consiste en ejecutar un servidor web local, entregar el archivo y realizar la llamada AJAX a localhost.
En términos de ayudarlo a escribir código para leer JSON, debe leer la documentación de jQuery.getJSON() :
http://api.jquery.com/jQuery.getJSON
Aquí hay una manera de hacerlo sin jQuery.
Primero crea esta función:
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); }Entonces puedes usarlo simplemente llamando a algo como esto:
loadJSON(function(json) { console.log(json); // this will log out the json object });