Reputation: 13
Let's say there are 3 divs in my html. Id's are:
I want first to load in data which is json from server on stepone div, if the return is '1' then print good on stepone div.
Then load in data on steptwo div, the data is json as well. So basically this is the process and the following is my code:
$(document).ready(function(){
var loadingone = $.post("stepone.php");
.done(function(dataone){
objone = JSON && JSON.parse(dataone) || $.parseJSON(dataone); //get json return from server
if (objone.status == "1") {
$("#stepone").html("good");
var loadingtwo = $.post("steptwo.php")
.done(function(datatwo){
objtwo = JSON && JSON.parse(datatwo) || $.parseJSON(datatwo);
if (objtwo.status == "1"){
$("#steptwo").html("good");
}
else
{
$("#steptwo").html("bad");
}
});
}
else
{
$("#stepone").html("message" + objone.codeurl);
}
});
});
So as you can see the code contains nested if statement and it doesn't look very clear. I am wondering if there is a better solution for this? thx ===updata=== here's the code after i edited, is it right?
var loadingone = $.post("stepone.php");
.done(function(dataone){
objone = JSON && JSON.parse(dataone) || $.parseJSON(dataone);
if (objone.status != "1"){
$("#stepone").html("bad" + objone.codeurl")
}
else{
$("#stepone").html("good");
var loadingtwo = $.post("steptwo.php");
.done(function(datatwo){
objtwo = JSON && JSON.parse(datatwo) || $.parseJSON(datatwo);
if (objtwo.status != "1"){
$("#steptwo").html("bad");
}
else
{
$("#steptwo").html("good");
}
}
}
Upvotes: 0
Views: 108
Reputation: 324650
Negate your expressions.
Rather than following a pattern like:
if A {
if B {
if C {
do stuff
}
else error C
}
else error B
}
else error A
Try this:
if !A {
error A
return
}
if !B {
error B
return
}
if !C {
error C
return
}
do stuff
This way, you keep the errors with their respective conditions, and you avoid deep nesting.
Upvotes: 3