通过 jquery 对 json 格式的数据使用真/假条件检查数据是否存在

Check data exist or not using true/false condition by jquery on json formatted data

本文关键字:数据 条件 检查 存在 是否 jquery json 格式 通过      更新时间:2023-09-26

嗨,伙计们,我对 php 和 jquery $.getJSON json_encode有一些问题。

我一直在尝试创建一个通知系统,并在phpjquery的帮助下做到了。我现在可以从数据库中获取数据,而无需重新加载/刷新页面。

我有来自database fetched数据,我在我的网站上显示它们,例如:-

Jquery代码

$.getJSON("notifi.php",function(data){  
$(".display_noti").empty(); // Clear out the div  
$.each(data.result,function(){  
     $(".display_noti").append("<div class='palnotific'>You got a  
          friend request from <strong>"+this['from']+"</strong><br></div>");  
   });  
});

php方面,我只是从table中获取数据,最后我encoded json格式的数据,这与我的问题无关。

这是我的 php 从那个 notifi.php 文件中生成的,我在那里对json格式过程进行了那些fetchedencoded

Json encoded格式

{"result":[{"from":"hancy061","to":"souraan061"}]}  

我的问题现在在我的jquery方面使用if and else条件如何检查该notifi.php中是否有值数据,或者我们可以说json格式数据?

如果您

知道data返回的是空的json数据还是有数据,请尝试像这样检查它:

$.getJSON("notifi.php",function(data){  
  // you can do checking here
  if ( data && data.length > 0 ) {
     $(".display_noti").empty(); // Clear out the div  
     $.each(data.result,function(){  
       $(".display_noti").append("<div class='palnotific'>You got a  
         friend request from <strong>"+this['from']+"</strong><br></div>");
     }); 
  }
  else {
    // do something here if no data
  }
});

或者也许data返回了一些值,即使属性中有一个空数据,例如刚刚返回{"result":[]},然后通过data.result.length进行检查

你可以

使用类似的东西

   if(data!=null && data!=undefined && data.result!=undefined && data.result.length!=undefined && data.result.length>0){
//Put your loop here
}

如果我在这里错了,人们会纠正我。