Skip to content

Instantly share code, notes, and snippets.

@uahim
Last active August 14, 2024 18:51
Show Gist options
  • Save uahim/502239e2c2d80886fa99e1fe3cee3b53 to your computer and use it in GitHub Desktop.
Save uahim/502239e2c2d80886fa99e1fe3cee3b53 to your computer and use it in GitHub Desktop.
XMLHttpRequest.js example
var getJSON = function(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'json'; // or html (returns as accessible document!) or text (default):
// https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseType
xhr.onload = function() {
var status = xhr.status;
if (status == 200) {
callback(null, xhr.response);
} else {
callback(status);
}
};
xhr.send();
};
getJSON(YOUR_URL, function(err, data) {
if (err != null) {
console.error(err);
} else {
console.log(data); // read text, parse javascript object or access DOM via document.<dowhatever>
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment