gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 15:42:04 24 4
gpt4 key购买 nike

我已成功从 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com