2016-11-16 47 views
1

代碼世界......顯示合適的消息時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 

但我只返回了[ ]當對象爲空時向控制檯發送。

要點是 - 當對象不爲空時,我可以相應地顯示消息。

當對象爲空時,顯示'沒有評論'。

請幫助,並提前謝謝。

+0

什麼代碼世界 – Conan

+0

@Conan - 這是一個信息時代,我們生活在一個世界的代碼。 –

回答

2

var obj = JSON.parse(data);正在返回一個空數組。當您嘗試執行.map時,您提供的回調函數從不執行,因爲它只在數組中的項目上執行。

而是你爲什麼不跳過這一切,只是做

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

是的!那正是我所需要的,而且它很有效。謝謝你,先生。非常感謝你。 –