When it comes to programming with AJAX, I find it challenging to maintain readable and understandable code.
Overview:
The basic concept is simple. I use an AJAX function called getServerData
to fetch data from the server. One of the arguments in this function is callbackFunc
, which gets invoked once the data is retrieved.
Here's the AJAX routine I typically follow to retrieve data:
function getServerData(urlAddress, params, callbackFunc, sender, method){
if (method !== "GET"){method = "POST";}
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
if (callbackFunc){callbackFunc(xhttp.responseText, sender);}
}
};
if (method == "GET"){
xhttp.open(method, urlAddress, true);
xhttp.send();
}
else {
xhttp.open(method, urlAddress, true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(params);
}
}
And here's a sample callback routine:
do_Select = function(responseText, sender){
alert(responseText);
}
So, whenever I need to load data and execute something afterwards, I utilize it like this:
getServerData("example.com/select.php", someParams, do_Select, this, "POST");
The issue:
However, my dilemma arises when my do_Select
function becomes too lengthy like this:
do_Select = function (responseText, sender) {
switch (responseText) {
case "one":
if (something1 === something2) {
//....
getServerData("example.com/select.php", someParams, callback2, this, "POST");
} else
{
//....
getServerData("example.com/select.php", someParams, callback3, this, "POST");
}
break;
case "two":
//....
getServerData("example.com/select.php", someParams, callback4, this, "POST");
break;
}
}
Having to declare multiple callback functions elsewhere in the code complicates the logic and readability as the code expands over time.
Is there a more efficient way to streamline and enhance the code for better readability?