You will need to request your json using the object Xmlhttprequest thus below:
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();
Then the object analyzes the return of the request made by the object Xmlhttprequest and checks that the httpd status is valid (200) and transforms the return of the file (string) to a json using the javascript function 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 serves to execute the code after the page load is complete.
Possible duplicate of Read and manipulate json data using jquery
– Rafael Salomão
In all the examples I’ve seen in other questions, they use the following syntax "$. getJSON('ajax/test.json', Function(data) {", but how would I call this function? I just want to execute the reading function of my code.
– user75204
This function is native to Jquery. You use jquery in your project?
– Rafael Salomão
I do not use Jquery.
– user75204