Skip to content

Instantly share code, notes, and snippets.

@davidhund
Created December 15, 2017 09:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidhund/21177763d930aac5a8c52bd30864ff94 to your computer and use it in GitHub Desktop.
Save davidhund/21177763d930aac5a8c52bd30864ff94 to your computer and use it in GitHub Desktop.
getJSON AJAX response, IE11 compat
/**
* Make AJAX call for JSON resource
* Supports IE11 and browsers that do not allow responseType='json'.
* https://mathiasbynens.be/notes/xhr-responsetype-json
* ----------------------------------------------------- */
var getJSON = function(url, successHandler, errorHandler) {
var xhr = typeof XMLHttpRequest != 'undefined' ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
var supportsJSON = (function() {
if (typeof XMLHttpRequest == 'undefined') { return false; }
var xhr = new XMLHttpRequest();
xhr.open('get', '/', true);
try {
// some browsers throw when setting `responseType` to an unsupported value
xhr.responseType = 'json';
} catch(error) { return false; }
return 'response' in xhr && xhr.responseType == 'json';
}());
xhr.open('get', url, true);
if (supportsJSON) { xhr.responseType = 'json'; }
xhr.onreadystatechange = function() {
var status = xhr.status;
var data;
// https://xhr.spec.whatwg.org/#dom-xmlhttprequest-readystate
if (xhr.readyState == 4) { // `DONE`
if (status == 200) {
successHandler && successHandler( supportsJSON ? xhr.response : JSON.parse(xhr.responseText));
} else {
errorHandler && errorHandler(status);
}
}
};
xhr.send();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment