Skip to content

Instantly share code, notes, and snippets.

@Rayraegah
Last active August 29, 2015 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Rayraegah/e44bcdbce25e32de9ca9 to your computer and use it in GitHub Desktop.
Save Rayraegah/e44bcdbce25e32de9ca9 to your computer and use it in GitHub Desktop.
Ajax xhr request
{"foo": 1, "bar": 2}
<p>This page gets the following data from <a href="data.json" title="Data file in JSON format">data.json</a>:</p>
<div id="data"></div>
<script src="xhr.js"></script>
var xhr = new XMLHttpRequest();
xhr.open("GET", "data.json");
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
var data = JSON.parse(xhr.responseText);
document.querySelector("#data").innerHTML = JSON.stringify(data);
}
}
/*
// can do this in Chrome, Firefox, etc.:
xhr.onload = function(event) {
var data = JSON.parse(this.response);
document.querySelector("#data").innerHTML = JSON.stringify(data);
}
*/
xhr.send();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment