Javascript 当JSON对象为空时显示适当的消息
我成功地从PHP脚本返回了JSON,但如果JSON对象为空,则无法显示相应的消息 消息显示在一个HTML UL标记中,ID为Javascript 当JSON对象为空时显示适当的消息,javascript,jquery,json,Javascript,Jquery,Json,我成功地从PHP脚本返回了JSON,但如果JSON对象为空,则无法显示相应的消息 消息显示在一个HTML UL标记中,ID为#precommentsload 下面是jQuery从PHP脚本发送和返回数据: $.post("api/searchComments.php", {uid:uid}, function(data) { if(data == '[]') // here's where I'm checking if JSON object is empty { c
#precommentsload
下面是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);
}
});
但我只在对象为空时才将[]返回控制台
关键是,当对象不为空时,我可以相应地显示消息
当对象为空时,它将显示“没有注释”。var obj=JSON.parse(数据)代码>正在返回一个空数组。当您尝试执行.map
时,您提供的回调函数永远不会执行,因为它只对数组中的项执行
相反,你为什么不跳过所有这些,直接去做呢
var htmlToInsert = '<li>There were no comments.</li>'
$('#precommentsload').html(htmlToInsert);
var htmlToInsert='没有评论。 '
$('#precommentsload').html(htmlToInsert);
是!!!!这就是我一直在寻找的,而且成功了。谢谢你,好先生。非常感谢你。
var htmlToInsert = '<li>There were no comments.</li>'
$('#precommentsload').html(htmlToInsert);