Last active
February 24, 2016 20:47
-
-
Save christianmendoza/3da722a1286cd1ce810e to your computer and use it in GitHub Desktop.
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
/* http://idiallo.com/javascript/ajax-without-jquery */ | |
var url = "http://jsonplaceholder.typicode.com/posts"; | |
var Ajax = { | |
xhr : null, | |
request : function (url, method, data, success, failure) { | |
if (!this.xhr) { | |
this.xhr = new XMLHttpRequest(); | |
} | |
var self = this.xhr; | |
self.onreadystatechange = function () { | |
if (self.readyState === 4 && self.status === 200) { | |
// the request is complete, parse data and call callback | |
var response = JSON.parse(self.responseText); | |
success(response); | |
} | |
else if (self.readyState === 4) { // something went wrong but complete | |
failure(); | |
} | |
}; | |
this.xhr.open(method, url, true); | |
this.xhr.send(); | |
} | |
}; | |
Ajax.request(url, "GET", null, function(data) { | |
console.log("success"); | |
}, function() { | |
console.log("failed"); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment