大家好,我有一些关于 json_encode
的问题php 和 jquery $.getJSON
.
我一直在尝试创建一个通知系统,并且是在 php
的帮助下完成的和 jquery
.我现在可以从数据库中获取数据而无需重新加载/刷新页面。
我有fetched
数据来自 database
我在我的网站上展示它们,例如:-
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
最后的格式与我的问题无关。
这是我的 php 从 notifi.php
中产生的结果我做这些的文件 fetched
和 encoded
在 json
格式化过程。
Json encoded
格式
{"result":[{"from":"hancy061","to":"souraan061"}]}
我的问题现在在我的 jquery
上侧面使用 if and else
condition 如何检查那个 notifi.php
中是否有值数据或者我们可以说 json
格式化数据?
最佳答案
如果您知道 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":[]}
,然后通过 数据.结果.长度
关于javascript - 通过 jquery 对 json 格式的数据使用 true/false 条件检查数据是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33470975/