Last active
February 3, 2016 19:52
-
-
Save janbiasi/657a03c7f9c8f26bbf00 to your computer and use it in GitHub Desktop.
ajax
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(window, undefined) { | |
var strEq = function(str1, str2) { | |
return str1.toLowerCase() === str2.toLowerCase(); | |
}; | |
var ajaxRequest = function(method, opts) { | |
opts = opts ? opts : {}; | |
opts.data = opts.data || null; | |
opts.success = opts.success || function() { }; | |
opts.error = opts.error || function(data, code) { | |
throw new Error("Ajax abortet with statuscode " + code); | |
}; | |
opts.async = opts.async || false; | |
opts.url = opts.url || null; | |
if(opts.url == null) { | |
return console.error("Can\'t create a request because the target url is empty"); | |
} | |
var xhr = new XMLHttpRequest(); | |
xhr.open(method, opts.url, opts.async); | |
xhr.onreadystatechange = function () { | |
if (xhr.readyState != 4 || xhr.status != 200) { | |
return opts.error(xhr.responseText, xhr.status); | |
} | |
opts.success(xhr.responseText); | |
}; | |
r.send(opts.data); | |
}; | |
var ajaxGet = function(opts) { | |
return ajaxRequest("GET", opts); | |
}; | |
var ajaxPost = function(opts) { | |
return ajaxRequest("POST", opts) | |
}; | |
var ajax = function(opts) { | |
if(strEq(opts.type, "get")) { | |
return ajaxGet; | |
} else { | |
return ajaxPost; | |
} | |
}; | |
window.ajax = ajax; | |
})(window); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment