Last active
August 29, 2015 14:01
-
-
Save reidev275/7b03f42a479be595391f to your computer and use it in GitHub Desktop.
ajax without jQuery
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
var ajax = (function (ajax, json) { | |
ajax.send = function (obj) { | |
var xmlhttp = new XMLHttpRequest(); | |
xmlhttp.onreadystatechange = function () { | |
if (xmlhttp.readyState == 4) { | |
if (xmlhttp.status >= 200 && xmlhttp.status < 300 && obj.complete) { | |
obj.complete(json.parse(xmlhttp.responseText)); | |
} | |
if (xmlhttp.status < 200 || xmlhttp.status >= 300) { | |
if (obj.error) obj.error(xmlhttp.response); | |
} | |
} | |
} | |
xmlhttp.open(obj.method, obj.url, true); | |
xmlhttp.setRequestHeader('Content-type', 'application/json'); | |
xmlhttp.send(obj.data); | |
}; | |
return ajax; | |
})(ajax || {}, JSON); |
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
ajax.send({ | |
url: 'http://myDomain.com/resource', | |
data: { | |
field: 'value' | |
}, | |
method: 'POST', | |
complete: function(data) { | |
//do something with data | |
}, | |
error: function(data) { | |
//handle error | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment