javascript - 通过 jquery 对 json 格式的数据使用 true/false 条件检查数据是否存在

标签 javascript jquery json

大家好,我有一些关于 json_encode 的问题php 和 jquery $.getJSON .

我一直在尝试创建一个通知系统,并且是在 php 的帮助下完成的和 jquery .我现在可以从数据库中获取数据而无需重新加载/刷新页面。

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

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 中产生的结果我做这些的文件 fetchedencodedjson格式化过程。

Json encoded格式

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

我的问题现在在我的 jquery 上侧面使用 if and else condition 如何检查那个 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":[]},然后通过 数据.结果.长度

关于javascript - 通过 jquery 对 json 格式的数据使用 true/false 条件检查数据是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33470975/

相关文章:

javascript - Angular 11 与 Webpack 5 - 向 IE11 用户显示消息

javascript - Chrome 扩展程序 : storage listener for only one stored variable

javascript - 在 vuex 操作中使用 fetch 方法

javascript - 如何将此字符串转换为某个数组?

javascript - JSON 获取结果 null

json - 用于 JSON Web 加密的 MIME 类型是什么

javascript - 如何将组添加到 buefy b-taginput?

javascript - window.onfocus 事件不会在 Google Chrome 中触发?

javascript - 点击触摸设备时如何防止 "ghost"点击超链接

Javascript:具有多个查询参数的嵌套 JSON api 请求