简体   繁体   中英

I have a JSON response like this, and I'm having trouble access the value for some reason

JSON response:

{ "success" : "false" }

Way I thought you access the data:

if (data.success[0] == "false") {
    alert("Login Successful");
}
else {
    alert("Login Failed");
}

It's going to the else condition. What am I doing wrong?

You are supposed to access an object not an array

if (data.success === false)

Your response should be

{ "success" : false }

otherwise you will need to compare to a string:

if (data.success === "false")

data.success is a string and not an array, so you do not need the [0] .

For your current JSON response, the if statement should read:

if(data.success === 'false') {
   ...
}

Like these guys said the object you are trying to access is not an array so you would not need the [0]

what this is doing is returning the letter at the index of [0] so if you were to log/alert data.success[0] you would get " F " because it is the first letter in the string that you are returning.

a more common practice would be to return a Boolean of false

{ "success" : false }
-----------------------^--------^
notice no " " marks

and then again no " " marks

-----------------------------------v-------v

if (data.success === false) {
  alert("Login Successful");
}
else {
  alert("Login Failed");
}

"false" is a string, not a boolean. You should compare data.success to "false"

if(data.success=="false") {

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM