Skip to content

Instantly share code, notes, and snippets.

@rmruano
Created January 25, 2013 21:31
Show Gist options
  • Save rmruano/4638071 to your computer and use it in GitHub Desktop.
Save rmruano/4638071 to your computer and use it in GitHub Desktop.
Simple Cross-browser XHR request with Cors support. Supported by any moder browser and IE>=8.
newCorsXHR = function(type, url) {
var xhr = false;
try {
xhr = new XMLHttpRequest();
} catch(e) {}
if (xhr && "withCredentials" in xhr) {
xhr.open(type, url, true); // Standard Cors request
} else if (typeof XDomainRequest != "undefined") {
xhr = new XDomainRequest(); // IE Cors request
xhr.open(type, url);
xhr.onload = function() {
this.readyState = 4;
if (this.onreadystatechange instanceof Function) this.onreadystatechange();
};
} else if (xhr) {
xhr.open(type, url, true);
};
return xhr;
};
// USAGE --------------------------------------------------------
// Request a new XHR object
var xhr = newCorsXHR("GET","http://co");
// Set future closure
xhr.onreadystatechange=function() {
if (xhr.readyState == 4) {
alert(xhr.responseText);
}
};
// Initiate the request
xhr.send();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment