简体   繁体   English

我有这样的JSON响应,由于某种原因我无法访问该值

[英]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.

相关问题 我在创建这样的供稿时遇到了麻烦 - I'm having trouble creating a feed like this 我无法更改输入中的值 - I'm having trouble changing the value in input 由于某种原因,我在验证表单时遇到问题,未输入名字或姓氏时不显示错误消息 - I'm having trouble validating my form for some reason the error messages do not appear when the forename or surname is not enterd 我在使用 javascript 中的.play function 时遇到了一些问题 - I'm having some trouble with the .play function in javascript 我在使用模板时遇到麻烦 - I'm having trouble with templates 我正在尝试将对象键“品牌”及其值放入一个新数组中,但我遇到了麻烦 - I’m trying to get the object key “brand” and its value into a new array but I’m having trouble 我必须连续展示三张卡片,但由于某种原因,我将卡片堆叠在一起 - I have to show three cards in a row, but for some reason I'm getting cards stacked over each other 我做了一个Javascript滑块,而CSS遇到了一些严重的麻烦。 - I made a Javascript slider and i'm having some serious trouble with the CSS. 我在理解此Javascript函数时遇到问题 - I'm having trouble understanding this Javascript function 我无法连接 websocket - I'm having trouble connecting websocket
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM