Skip to content

Instantly share code, notes, and snippets.

@thealscott
Created January 22, 2014 14:53
Show Gist options
  • Save thealscott/8560049 to your computer and use it in GitHub Desktop.
Save thealscott/8560049 to your computer and use it in GitHub Desktop.
XHR ajax snippet (via Remy)
function request(type, url, opts, callback) {
var xhr = new XMLHttpRequest(),
fd;
if (typeof opts === 'function') {
callback = opts;
opts = null;
}
xhr.open(type, url);
if (type === 'POST' && opts) {
fd = new FormData();
for (var key in opts) {
fd.append(key, JSON.stringify(opts[key]));
}
}
xhr.onload = function () {
callback(JSON.parse(xhr.response));
};
xhr.send(opts ? fd : null);
}
var get = request.bind(this, 'GET');
var post = request.bind(this, 'POST');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment