javascript - 当 JSON 对象为空时显示适当的消息

标签 javascript jquery json

我已成功从 PHP 脚本返回 JSON,但如果 JSON 对象为空,则无法显示相应的消息。

消息显示在 ID 为 #precommentsload 的 HTML UL 标记中。

下面是 jQuery 从 PHP 脚本发送和返回数据:

 $.post("api/searchComments.php", {uid:uid}, function(data)
 {
   if(data == '[]') // here's where I'm checking if JSON object is empty
   {
     console.log('no data'); // console displays this message when empty
     // here's where I'm trying to output a message
     var obj = JSON.parse(data);
     $('#precommentsload').empty();
     var htmlToInsert = obj.map(function(item)
     {
       return '<li>There were no comments.</li>';
     }).join('');
     $('#precommentsload').html(htmlToInsert);
   }
   else
   {
     console.log(data); // when object returns data, I can see it here
     var obj = JSON.parse(data)
     $('#precommentsload').empty();
     var htmlToInsert = obj.map(function (item)
     {
       return '<li><b>' + item.add_date + ' - ' + item.add_user + '</b> 
       <br />' + item.comment.replace(/\r\n/g, '<br />') + '</li>';
       // no problem displaying comments when object is not empty
     }).join('');
     $('#precommentsload').html(htmlToInsert);      
   }
 });

在 $.post 之后,我尝试了这个 IF 语句:

 if(data == []) // without the single quotes

但我只在对象为空时才将 [] 返回到控制台。

关键是,当对象不为空时,我可以相应地显示消息。

它会在对象为空时显示“没有评论”。

最佳答案

var obj = JSON.parse(data); 返回一个空数组。当您尝试执行 .map 时,您提供的回调函数永远不会执行,因为它只对数组中的项目执行。

相反,你为什么不跳过所有这些而直接去做

var htmlToInsert = '<li>There were no comments.</li>'
$('#precommentsload').html(htmlToInsert);

关于javascript - 当 JSON 对象为空时显示适当的消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40638093/

相关文章:

javascript - 谷歌地图 event.addListener 对象未定义

javascript - 如何按顺序 .append() 创建的元素到先前添加的元素

教如何编写这样的代码的 jQuery 教程/书籍

java - Spring Boot GET 请求 API

json - 使用JSON API列出谷歌云存储中文件夹内的文件和文件夹

javascript - 在 Chrome 中对无序列表的列表项进行排序

javascript - 需要 jQuery 鼠标悬停或悬停帮助

javascript - 当有波斯语字符时,如何改变文本区域的方向?

javascript - 在 Javascript 字符串中查找 <img> 标签的 src 属性值

javascript - 上传文件时使用 JavaScript 确定文件类型