Skip to content

Instantly share code, notes, and snippets.

@texas2010 texas2010/ajaxFunction.js
Last active Aug 27, 2017

Embed
What would you like to do?
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
You can’t perform that action at this time.