Skip to content

Instantly share code, notes, and snippets.

@isorna
Last active December 31, 2015 20:09
Show Gist options
  • Save isorna/8038062 to your computer and use it in GitHub Desktop.
Save isorna/8038062 to your computer and use it in GitHub Desktop.
function createCORSRequest (poMethod, pcURL) {
var oXHR = new XMLHttpRequest();
if ('withCredentials' in oXHR) {
// Check if the XMLHttpRequest object has a "withCredentials" property.
// "withCredentials" only exists on XMLHTTPRequest2 objects.
oXHR.open(poMethod, pcURL, true);
} else if (typeof XDomainRequest != 'undefined') {
// Otherwise, check if XDomainRequest.
// XDomainRequest only exists in IE, and is IE's way of making CORS requests.
oXHR = new XDomainRequest();
oXHR.open(poMethod, pcURL);
} else {
// Otherwise, CORS is not supported by the browser.
oXHR = null;
}
return oXHR;
}
function makeCorsRequest (pcURL) {
var oXHR = createCORSRequest('GET', pcURL);
if (!oXHR) {
throw new Error('CORS not supported');
} else {
/* Optional:
oXHR.withCredentials = true;*/
oXHR.onload = function() {
var cResponseText = oXHR.responseText;
console.log(cResponseText);
// process the response.
};
oXHR.onerror = function() {
console.error('There was an error!');
};
oXHR.send();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment