Last active
August 14, 2024 18:51
-
-
Save uahim/502239e2c2d80886fa99e1fe3cee3b53 to your computer and use it in GitHub Desktop.
XMLHttpRequest.js example
This file contains 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 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