[英]I have a JSON response like this, and I'm having trouble access the value for some reason
JSON response: JSON响应:
{ "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]
. data.success
是字符串,而不是数组,因此不需要[0]
。
For your current JSON response, the if
statement should read: 对于当前的JSON响应,
if
语句应为:
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] 就像这些家伙说的那样,您尝试访问的对象不是数组,因此不需要[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. 这是在返回索引 [0]处的字母,因此,如果要记录/警告
data.success[0]
,则将获得“ F”,因为它是返回字符串中的第一个字母。
a more common practice would be to return a Boolean of false
更常见的做法是返回布尔值
false
{ "success" : false }
-----------------------^--------^ ----------------------- ^ ^ --------
notice no " " marks 注意没有标记
and then again no " " marks 然后再没有“”标记
-----------------------------------v-------v ----------------------------------- v ------- v
if (data.success === false) {
alert("Login Successful");
}
else {
alert("Login Failed");
}
"false" is a string, not a boolean. “ false”是字符串,而不是布尔值。 You should compare data.success to "false"
您应该将data.success与“ false”进行比较
if(data.success=="false") {
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.