Last active
August 29, 2015 14:03
-
-
Save Rayraegah/e44bcdbce25e32de9ca9 to your computer and use it in GitHub Desktop.
Ajax xhr request
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{"foo": 1, "bar": 2} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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