Last active
August 29, 2015 14:23
-
-
Save tswaters/a771eee2f8cfff09b60b to your computer and use it in GitHub Desktop.
ajax helper
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function ajax (opts) { | |
if (this instanceof ajax) throw new Error("stop instantiating me!"); | |
if (!opts) throw new Error("pass opts, dummy.") | |
if (!opts.url) throw new Error("pass url, dummy"); | |
if (!opts.method) throw new Error("pass method, dummy"); | |
var callbacks = { | |
success: [], | |
failure: [], | |
always: [] | |
}; | |
var ret = Object.keys(callbacks).reduce(function(obj, key) { | |
obj[key] = function (cb) { callbacks[key].push(cb); return ret; }; | |
return obj; | |
}, {}); | |
var req = new XMLHttpRequest(); | |
req.open(opts.method.toUpperCase(), opts.url); | |
req.onreadystatechange = function () { | |
if (!(req.readyState === 4)) { return; } | |
var ok = req.status >= 200 && req.status < 400; | |
var fns = callbacks[ok ? "success" : "failure"]; | |
fns.forEach(function (cb) { cb(req); }); | |
callbacks.always.forEach(function (cb) {cb(req); }); | |
}; | |
req.send(opts.data); | |
return ret; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment