Last active
December 24, 2015 22:49
-
-
Save Scribblerockerz/6875954 to your computer and use it in GitHub Desktop.
Minimal ajax function.
No fallback for older browsers (lt IE7).
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(exports){ | |
exports.ajax = function(opt){ | |
var req = new XMLHttpRequest(), | |
res, | |
opt = opt || {}; | |
//defaults | |
opt.success = opt.success || function(){}; | |
opt.params = opt.params || {}; | |
opt.type = opt.type || 'GET'; | |
opt.contentType = opt.contentType || "application/x-www-form-urlencoded"; | |
//default events | |
req.onerror = opt.failure; | |
req.onabort = opt.abort; | |
req.onload = opt.load; | |
opt._params = ""; | |
for(p in opt.params){ | |
opt._params += p +"="+ encodeURI(opt.params[p]) +"&"; | |
} | |
req.onreadystatechange = function(){ | |
if(req.readyState < 4) return; | |
if(req.status < 200 && req.status > 206) return; | |
try { | |
res = JSON.parse(req.responseText); | |
}catch(e){ | |
res = req.responseText; | |
} | |
opt.success(res, req); | |
} | |
if(opt.type == 'GET'){ | |
req.open(opt.type, opt.url+"?"+opt._params, true); | |
req.send(null); | |
}else{ | |
// default alternative is POST | |
req.open(opt.type, opt.url, true); | |
req.setRequestHeader("Content-type", opt.contentType); | |
req.send(opt._params); | |
} | |
} | |
})(window); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment