Skip to content

Instantly share code, notes, and snippets.

@umbrae
Created May 4, 2011 17:14
Show Gist options
  • Select an option

  • Save umbrae/955596 to your computer and use it in GitHub Desktop.

Select an option

Save umbrae/955596 to your computer and use it in GitHub Desktop.
A simple raw CORS XMLHttp Library. Fully untested, but the jist should be there. Has no support for failing cases currently.
/**
* A simple CORS XMLHttp Library. Fully untested, but the jist should be there. Has no support for failing cases currently
*
* Should work in FF4, Webkit, and IE8+
* @param method string - like GET or POST
* @param url string - the URL to attempt to fetch
* @param data Object - a dictionary of parameters to pass if we're POSTing
* @param callback Function - a callback to be returned on success.
**/
function cxhr(method, url, data, callback) {
var request = new XMLHttpRequest(),
stateChange = function () {
if (this.readyState === 4) { /* 4 === DONE */
return callback(this);
}
},
encodedData = "",
dataArr = [],
d;
if (typeof data === "object") {
for (d in data) {
if (data.hasOwnProperty(d)) {
dataArr.push(d + "=" + encodeURIComponent(data[d]));
}
}
encodedData = dataArr.join('&');
}
if ("withCredentials" in request) {
// Standards-based Browser
request.open(method, url, true); /* method, url, async */
request.onreadystatechange = stateChange;
request.send(data);
} else if (XDomainRequest) {
// IE8
var xdr = new XDomainRequest();
xdr.open(method, url);
xdr.send();
xdr.onload = callback;
}
// If they got here, there was no support for CORS in the first place.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment