Last active
August 27, 2017 17:42
-
-
Save texas2010/ec04d23b0d7373f217506e26ce7d0198 to your computer and use it in GitHub Desktop.
my own ajax function.
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 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