Skip to content

Instantly share code, notes, and snippets.

@eriwen
Created May 26, 2012 15:54
Show Gist options
  • Save eriwen/2794392 to your computer and use it in GitHub Desktop.
Save eriwen/2794392 to your computer and use it in GitHub Desktop.
Simple cross-domain Javascript function
/**
* 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'));
}
}
@emrebayrm
Copy link

hi I have used your code , and I get a 415 code returned. is it about bad connection or am I need configure different thing, So did you have ever seen that before ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment