You will need to place a request for your json using the XMLHttpRequest object as follows:
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
document.getElementById("demo").innerHTML = myObj.name;
}
};
xmlhttp.open("GET", "json_demo.txt", true);
xmlhttp.send();
Next, the object parses the return of the request made by the XMLHttpRequest object and verifies that the status httpd is valid (200) and transforms the return of the file (string) to a json using the function javascript JSON.parse , then you can read the json entries one by one to your variable as you did above in your example.
Deepen your knowledge here: read Json with javascript
To run when the page loads you have to use an event, like this:
window.onload = function(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
document.getElementById("demo").innerHTML = myObj.name;
}
};
xmlhttp.open("GET", "json_demo.txt", true);
xmlhttp.send();
}
window.onload is used to run the code after page load is complete.