Skip to content

Instantly share code, notes, and snippets.

@texas2010
Last active August 27, 2017 17:42
Show Gist options
  • Save texas2010/ec04d23b0d7373f217506e26ce7d0198 to your computer and use it in GitHub Desktop.
Save texas2010/ec04d23b0d7373f217506e26ce7d0198 to your computer and use it in GitHub Desktop.
my own ajax function.
var ajaxFunction = function (object) {
var problemMessage = function (message) {
console.error(message);
};
if (!Array.isArray(object) && typeof object == "object") {
object.method = object.method || "GET"; // Default Value for method
object.type = object.type || "text"; // Default Value for type
if(!object.url) { // Check URL
delete object.url;
problemMessage("'url:' is required in the ajaxFunction().");
}
if(typeof object.callback !== 'function') { // Check Function
problemMessage("'callback:' is required in the ajaxFunction().");
}
if(object.url && typeof object.callback == 'function') { // Check url and function
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
object.callback(this.response);
}
};
request.open(object.method, object.url);
request.responseType = object.type;
request.send();
}
} else {
problemMessage("{} is required in the ajaxFunction().");
}
}
// Example code
ajaxFunction({
method: "GET",
url: "URL",
type: "json",
callback: functionName
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment