Skip to content

Instantly share code, notes, and snippets.

@davidgarsan
Created August 6, 2017 09:12
Show Gist options
  • Save davidgarsan/38e17667ad79ac3d36644e42a3ba2e49 to your computer and use it in GitHub Desktop.
Save davidgarsan/38e17667ad79ac3d36644e42a3ba2e49 to your computer and use it in GitHub Desktop.
XHR
var xhr = function() {
var xhr = new XMLHttpRequest();
var mapper = function(data) {
return Object.keys(data).map(function(k) {
return encodeURIComponent(k) + '=' + encodeURIComponent(data[k])
}).join('&');
};
return function(method, url, data, success, error, isJSON, headers) {
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status === 200 && success) {
success(isJSON? JSON.parse(xhr.responseText) : xhr.responseText);
} else if (error) {
error();
}
}
};
url += (data && method === 'GET') ? mapper(data) : '';
xhr.open(method, url);
if (headers) {
for(header in headers) {
xhr.setRequestHeader(header, headers[header]);
};
}
// xhr.setRequestHeader("Content-Type", "application/json");
xhr.send((data && method === 'POST') ? JSON.stringify(data) : '');
};
}();
// xhr('GET', 'url', JSONheaders, function(data){console.log(JSON.parse(data))});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment