Skip to content

Instantly share code, notes, and snippets.

@etsms
Forked from rmruano/Cross-browser XHR for CORS requests
Last active April 3, 2017 19:03
Show Gist options
  • Save etsms/f1c6562bb2b9aa8fdb3970199718881f to your computer and use it in GitHub Desktop.
Save etsms/f1c6562bb2b9aa8fdb3970199718881f to your computer and use it in GitHub Desktop.
Simple Cross-browser XHR request with Cors support. Supported by any moder browser and IE>=8.
function ajax(type, url, data, callback) {
var xhr = new(this.XMLHttpRequest || ActiveXObject)('MSXML2.XMLHTTP.3.0');
var req = [];
for(var item in data) {
req.push(encodeURIComponent(item) + "=" + encodeURIComponent(data[item]));
}
data = req.join("&");
xhr.open(data ? 'POST' : 'GET', url, 1);
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.open(type, url, true);
xhr.onload = function() {
if (this.status == 200) {
callback(JSON.parse(this.responseText), this);
return;
};
};
xhr.send(data);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment