Created
June 17, 2016 19:59
-
-
Save gfscott/4c728a7700c691d5f0f819c2ad666a8d to your computer and use it in GitHub Desktop.
A simple, reusable AJAX helper function for GETting JSON
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
// ----------------------------------------------------------------------------- | |
// SIMPLE REUSABLE AJAX GET JSON FUNCTION | |
// A frequent thing I find myself writing in projects is a simple function to | |
// get JSON via AJAX. This simple helper does that in a sensible way without | |
// needing jQuery or a needlessly complex standalone Ajax library. Get data | |
// so you can do stuff with it. That’s all it does. No POSTing, no crazy edge- | |
// case error handling. | |
function getJson(url, callback) { | |
"use strict"; | |
var request = new XMLHttpRequest(); | |
request.open('GET', url, true); | |
request.onload = function() { | |
if (request.status >= 200 && request.status < 400) { | |
var json = JSON.parse(request.responseText); | |
callback(json); | |
} else { | |
// server error | |
console.error("There was an error connecting to the server. The error code was " + request.status); | |
return; | |
} | |
}; | |
request.onerror = function() { | |
console.error( "There was an error connecting to the server." ); | |
return; | |
}; | |
request.send(); | |
} | |
// USAGE: | |
// | |
// getJson("https://randomuser.me/api/", function(data){ | |
// // Do stuff with the returned data | |
// console.log(data.results[0].name.first); | |
// }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Great job! It's very helpful. Thank you.