Created
January 25, 2013 21:31
-
-
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.
This file contains hidden or 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
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