Skip to content

Instantly share code, notes, and snippets.

@bitsmanent
Last active January 18, 2017 16:05
Show Gist options
  • Save bitsmanent/701ca9a80cf02f1f8b0c to your computer and use it in GitHub Desktop.
Save bitsmanent/701ca9a80cf02f1f8b0c to your computer and use it in GitHub Desktop.
Send XMLHttpRequest requests
function xhr(method, hdrs, action, data, callback) {
var r = new XMLHttpRequest();
r.onreadystatechange = function() {
if(r.readyState == 4 && r.status == 200)
callback(JSON.parse(r.responseText)); /* always expect JSON */
};
switch(method.toUpperCase()) {
case "POST":
r.open(method, action, true);
if(data && !(data instanceof FormData)) {
r.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
data = serialize(data);
}
break;
case "GET":
if(data) {
data = serialize(data);
action += ((action.indexOf('?') == -1) ? '?' : '&')+data;
data = null;
}
r.open(method, action, true);
break;
default:
console.error(method+": method not supported");
return;
}
if(hdrs)
for(var h in hdrs)
r.setRequestHeader(h, hdrs[h]);
r.send(data);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment