简体   繁体   中英

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.

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 .

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).

How can I fix this code?

UPDATE

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 . undefined , null , false , 0 , an empty string evaluates to 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. As shown in the JSON you want to check if the value from the response object is null. So just check

if( data.longtext_dec !== null ) 

Here is very well explained:

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 || 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); 

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