代碼世界......顯示合適的消息時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);
}
});
的$。員額後,我想這個if語句:
if(data == []) // without the single quotes
但我只返回了[ ]當對象爲空時向控制檯發送。
要點是 - 當對象不爲空時,我可以相應地顯示消息。
當對象爲空時,顯示'沒有評論'。
請幫助,並提前謝謝。
什麼代碼世界 – Conan
@Conan - 這是一個信息時代,我們生活在一個世界的代碼。 –