Skip to content

Instantly share code, notes, and snippets.

@souparno
Forked from eriwen/cors.js
Created July 21, 2014 13:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save souparno/4b05430fc00c2fc41888 to your computer and use it in GitHub Desktop.
Save souparno/4b05430fc00c2fc41888 to your computer and use it in GitHub Desktop.
/**
* Make a X-Domain request to url and callback.
*
* @param url {String}
* @param method {String} HTTP verb ('GET', 'POST', 'DELETE', etc.)
* @param data {String} request body
* @param callback {Function} to callback on completion
* @param errback {Function} to callback on error
*/
function xdr(url, method, data, callback, errback) {
var req;
if(XMLHttpRequest) {
req = new XMLHttpRequest();
if('withCredentials' in req) {
req.open(method, url, true);
req.onerror = errback;
req.onreadystatechange = function() {
if (req.readyState === 4) {
if (req.status >= 200 && req.status < 400) {
callback(req.responseText);
} else {
errback(new Error('Response returned with non-OK status'));
}
}
};
req.send(data);
}
} else if(XDomainRequest) {
req = new XDomainRequest();
req.open(method, url);
req.onerror = errback;
req.onload = function() {
callback(req.responseText);
};
req.send(data);
} else {
errback(new Error('CORS not supported'));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment