2015-11-02 14 views
1

嗨,大家好,我有一些問題關注php和jQuery的json_encode$.getJSON檢查數據是否存在或使用jQuery格式的數據上的jquery的真/假條件

我一直嘗試創建一個通知系統,我在phpjquery的幫助下做到了這一點。我現在可以從數據庫獲取數據而無需重新加載/刷新頁面。

我從databasefetched數據,我在我的網站喜歡展示他們: -

Jquery代碼

$.getJSON("notifi.php",function(data){ 

$(".display_noti").empty(); // Clear out the div 

$.each(data.result,function(){ 

    $(".display_noti").append("<div class='palnotific'>You got a 
      friend request from <strong>"+this['from']+"</strong><br></div>"); 

    }); 

}); 

php方面我只是讀取數據從table和我encoded那些在json格式末尾這是不關心我的問題。

這是從notifi.php文件,其中我做了我的json格式處理這些fetchedencoded我的PHP產品。現在

Json encoded格式

{"result":[{"from":"hancy061","to":"souraan061"}]} 

我的問題是關於使用if and else條件我jquery身邊,我怎麼能檢查是否有數值數據或者沒有在notifi.php,或者我們可以對json格式的數據說?

+0

嘗試'data.result.length'? –

+0

兄弟我不知道如何檢查它在jQuery的一面so..can你可以通過使用一些真正的假數據存在或不存在的一些正確的錯誤條件,並做一些如果存在,做一些如果不存在。我想用if其他條件可以告訴我一些答案。 –

回答

1

如果你知道data是否返回空的JSON數據或有數據,那麼請嘗試檢查它像這樣:

$.getJSON("notifi.php",function(data){ 
    // you can do checking here 
    if (data && data.length > 0) { 
    $(".display_noti").empty(); // Clear out the div 
    $.each(data.result,function(){ 
     $(".display_noti").append("<div class='palnotific'>You got a 
     friend request from <strong>"+this['from']+"</strong><br></div>"); 
    }); 
    } 
    else { 
    // do something here if no data 
    } 
}); 

也許data返回一定的價值,甚至有內部性質的空數據,例如剛回來{"result":[]} ,然後檢查它通過data.result.length

+0

感謝您的答案bro.It工程很好。 :) Ya,我的json數據也返回了一些值。我把它們保存在一個數組中,鍵名爲'result'和'value',其中兩列'from'和'to'.使用'data.result.length'完成工作:) –

+0

不錯。很高興聽到這個消息,歡迎你 –

1

您可以使用類似

if(data!=null && data!=undefined && data.result!=undefined && data.result.length!=undefined && data.result.length>0){ 
//Put your loop here 
} 

人糾正我,如果我錯了這裏。