Skip to content

Instantly share code, notes, and snippets.

@artificemm
Forked from pwittchen/loadJson.js
Created September 11, 2016 01:33
Show Gist options
  • Save artificemm/b9973794c4dc0cbdb584d0c7a725da55 to your computer and use it in GitHub Desktop.
Save artificemm/b9973794c4dc0cbdb584d0c7a725da55 to your computer and use it in GitHub Desktop.
Loading JSON file with JavaScript. Please note: it won't run as a "local" script. JavaScript does not allow to load local files due to security reasons. You should deploy it on the server in order to load JSON file.
function loadJson(callback) {
var XmlHttpRequest = new XMLHttpRequest();
XmlHttpRequest.overrideMimeType("application/json");
XmlHttpRequest.open('GET', 'file.json', true);
XmlHttpRequest.onreadystatechange = function () {
if (XmlHttpRequest.readyState == 4 && XmlHttpRequest.status == "200") {
// .open will NOT return a value
// but simply returns undefined in async mode so use a callback
callback(XmlHttpRequest.responseText);
}
}
XmlHttpRequest.send(null);
}
loadJson(function(response) {
jsonResponse = JSON.parse(response);
console.log(jsonResponse);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment