Skip to content

Instantly share code, notes, and snippets.

@ariesmcrae
Created July 9, 2014 06:21
Show Gist options
  • Save ariesmcrae/99c844f45d2e1d089a6f to your computer and use it in GitHub Desktop.
Save ariesmcrae/99c844f45d2e1d089a6f to your computer and use it in GitHub Desktop.
Read external JSON file using JavaScript
<!doctype html>
<html>
<head>
<script>
function init() {
loadJSON(function (response) {
displayJSON(response);
});
} // init
function loadJSON(callback) {
var xhr = new XMLHttpRequest();
xhr.overrideMimeType('application/json');
xhr.open('GET', 'scheduler.json', true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == '200') {
callback(xhr.responseText);
}
};
xhr.send(null);
}
function displayJSON(response) {
var scheduler = JSON.parse(response);
var myDiv = document.getElementById('MyDiv');
var str = '';
for (var i = 0; i < scheduler.length; i++) {
str += 'id=' + scheduler[i].id + ' '
+ 'name=' + scheduler[i].name + ' '
+ 'isOn=' + scheduler[i].isOn + ' '
+ 'count=' + scheduler[i].count + ' '
+ 'date=' + scheduler[i].date + '<br/><br/>';
}
myDiv.innerHTML = str;
}
</script>
<style>
div { font-family: courier; }
</style>
</head>
<body onload="init()">
<div id="MyDiv" />
<body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment