Vanilla JavaScript $.getJSON version with callback

// Remember XHMLHTTP requests are asynchronous!! function getJSON(url, callback) { var xhr = new XMLHttpRequest(); xhr.open("GET", url, true); xhr.onload = function (e) { if (xhr.readyState === 4) { if (xhr.status === 200) { var res = xhr.responseText; // Executes your callback with the // response already parsed into JSON callback(JSON.parse(res)); } else { // Server responded with some error console.error(xhr.statusText); } // End of verifying response status } // Please read: http://www.w3schools.com/ajax/... // .../ajax_xmlhttprequest_onreadystatechange.asp }; // End of what to do when the response is answered // What to do if there's an error with the request xhr.onerror = function (e) { console.error(xhr.statusText); }; // End of error handling // Send the request to the server xhr.send(null); } // End of getJSON function //================================================// // EXAMPLE OF USE WITH GITHUB API // //================================================// var apiURL = "https://api.github.com/users/luishendrix92"; getJSON(apiURL, function(userInfo) { console.log(userInfo); }); // End of request // -> You should now see an object that contains info // about my github account profile.
How to do a simple getJSON replacement for vanilla javascript without the need of Angular's HTTP module or jQuery's $.getJSON method. Careful, this does not work (apparently) with JSONP requests.

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.