Skip to content

Instantly share code, notes, and snippets.

@enricolucia
Created January 15, 2015 15:15
Show Gist options
  • Save enricolucia/a915df6485fd379c7675 to your computer and use it in GitHub Desktop.
Save enricolucia/a915df6485fd379c7675 to your computer and use it in GitHub Desktop.
XMLHTTPRequest Polyfill
function makeRequest(url,callback,context) {
var httpRequest = null;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
try {
httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
console.log('error');
}
}
}
if (!httpRequest) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
function serveContent(){
if (httpRequest.readyState === 4) {
if (httpRequest.status === 200) {
callback.call(context,JSON.parse(httpRequest.responseText));
} else {
console.log('There was a problem with the request.');
}
}
}
httpRequest.onreadystatechange = serveContent;
httpRequest.open('GET', url);
httpRequest.send();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment