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