Created
December 15, 2017 09:40
-
-
Save davidhund/21177763d930aac5a8c52bd30864ff94 to your computer and use it in GitHub Desktop.
getJSON AJAX response, IE11 compat
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
/** | |
* 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