[英]Ajax check value of data
I'm getting data as JSON response and each time one of my fields is empty and one has value so I need to make if
statement to check which one has value and print that one. 我正在获取数据作为JSON响应,并且每当我的一个字段为空且一个字段具有值时,因此我需要执行
if
语句来检查哪个字段具有值并打印该字段。
So far I tried: 到目前为止,我尝试了:
if(data.longtext_dec != ''){
var ress = data.longtext_dec;
} else {
var ress = data.text_dec;
}
and 和
if($.trim(data.longtext_dec) === '')
{
var ress = data.longtext_dec;
} else {
var ress = data.text_dec;
}
each time the code keeps printing longtext_dec
or show both as null
. 每次代码继续打印
longtext_dec
或将两者都显示为null
。
So I need help to get this right, the result of this ress
I want to append it in my view (either this or that). 因此,我需要帮助来完成此操作,我想将此
ress
的结果附加到我的视图中(此或该)。
How can I fix this code? 如何解决此代码?
network response tab: 网络响应标签:
product_id 15
specification_id 5
text_dec ddd
longtext_dec null
id 69
payload 有效载荷
{"product_id":"15","specification_id":"5","text_dec":"ddd","longtext_dec":null,"id":69}
Just use if (data.longtext_desc)
it's a way to check if data variable evaluates to true
. 只需使用
if (data.longtext_desc)
这是一种检查data变量的值是否为true
。 undefined
, null
, false
, 0
, an empty string evaluates to false
. undefined
, null
, false
, 0
,一个空字符串的计算结果为false
。
var ress; // undefined
if (data.longtext_desc) {
ress = data.longtext_desc;
} else {
ress = data.text_dec;
}
Optionally use a ternary operator: (可选)使用三元运算符:
var ress = data.longtext_desc ? data.longtext_desc : data.text_dec;
There is a difference between empty string, null, undefined and boolean true/false. 空字符串,null,undefined和布尔值true / false之间有区别。 As shown in the JSON you want to check if the value from the response object is null.
如JSON中所示,您要检查响应对象中的值是否为null。 So just check
所以只要检查一下
if( data.longtext_dec !== null )
Here is very well explained: 这里有很好的解释:
https://stackoverflow.com/a/27550756/3868104 https://stackoverflow.com/a/27550756/3868104
Optional you can check for whatever you want for example: 可选,您可以检查所需内容,例如:
if( data.longtext_dec !== "" )
and so on. 等等。
you can leverage javascript || 您可以利用javascript || operator as below
运算符如下
var res = data.longtext_dec || data.text_dec;
Try this : 尝试这个 :
var data = {"product_id":"15","specification_id":"5","text_dec":"ddd","longtext_dec":null,"id":69}; var ress; (data.longtext_dec !== null) ? ress = data.longtext_dec : ress = data.text_dec; console.log(ress);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.