Skip to content

Instantly share code, notes, and snippets.

@luisenriquecorona
Created June 7, 2019 00:14
Show Gist options
  • Save luisenriquecorona/74fad2dc211a7d4c908f69882726182e to your computer and use it in GitHub Desktop.
Save luisenriquecorona/74fad2dc211a7d4c908f69882726182e to your computer and use it in GitHub Desktop.
Checks the “Content-Type” header of the response and handles “application/json” responses specially. Another response type that you might want to “decode” specially is “application/javascript” or “text/javascript”.
// Issue an HTTP GET request for the contents of the specified URL.
// When the response arrives, pass it to the callback function as a
// parsed XML Document object, a JSON-parsed object, or a string.
function get(url, callback) {
var request = new XMLHttpRequest(); // Create new request
request.open("GET", url); // Specify URL to fetch
request.onreadystatechange = function() { // Define event listener
// If the request is compete and was successful
if (request.readyState === 4 && request.status === 200) {
// Get the type of the response
var type = request.getResponseHeader("Content-Type");
// Check type so we don't get HTML documents in the future
if (type.indexOf("xml") !== -1 && request.responseXML)
callback(request.responseXML); // Document response
else if (type === "application/json")
callback(JSON.parse(request.responseText)); // JSON response
else
callback(request.responseText); // String response
}
};
request.send(null); // Send the request now
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment