I am trying to read from a local myjson.json file and print its content to my index.html. I am using the following JavaScript code:
function getJSON() {
var xhr = new XMLHttpRequest();
xhr.open('GET', '/myfolder/myjson.json', false);
xhr.onreadystatechange = function () {
if (xhr.readyState == XMLHttpRequest.DONE) {
var response = xhr.responseText;
console.log("response: " + response); //Correctly prints JSON content to console
return response; //response is undefined when called from html
}
}
xhr.send(null);
}
I am calling the function getJSON() like so:
document.getElementById("contentOfJSON").innerHTML += "JSON: "+getJSON();
This prints out the content of myjson.json correctly to console.log, but my HTML-Element "contentOfJSON" contains only "JSON: undefined". Why am I getting an undefined response eventhough the console.log is working?