-
-
Save jinweijie/11e731c9b07f53bdf52f to your computer and use it in GitHub Desktop.
JavaScript CORS helper method. Read more about CORS here: http://www.html5rocks.com/en/tutorials/cors/http://www.nczonline.net/blog/2010/05/25/cross-domain-ajax-with-cross-origin-resource-sharing/
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
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 { | |
/* For windows authentication, must be withCredentials = true*/ | |
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.statusText); | |
}; | |
oXHR.send(); | |
} | |
} | |
makeCorsRequest ('http://localhost:9000/api/Values'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment