php - 检查 JSON 的响应是否为空

标签 php javascript jquery json jsonp

我正在通过 JSON 从 MySQL 获取一些数据。但是我想确定响应是否为空,如果它不为空我会显示返回的信息,否则我会显示一条消息。

我尝试了多种可能的解决方案,例如检查 JSON 响应的长度,检查项目严重性是否存在,如果不存在则假设它为 null 等。

这是我的代码片段:

var data = $.ajax({
    type: 'GET',
    url: 'http://www.mydomain.com/php/loaddata.php?&jsoncallback=?',
    dataType: 'JSONp',
    timeout: 5000,
    success: function(data) {
        $.each(data, function(i,item){
            if (item.Severity == 1) {   
                // Do Something
                .....

当JSON找到数据时,回复是这样的: 更新:

([{"Severity":"1","Latitude":"35.872883","Longitude":"14.449133","Address":"Some Address 1","Heading":"25","Timestamp":"2012-12-28 10:15:03"},{"Severity":"2","Latitude":"35.871269","Longitude":"14.501580","Address":"Some Address 2","Heading":"80","Timestamp":"2012-12-28 10:15:31"}]);

否则如果没有找到数据,JSON 返回:

([]);

最佳答案

因为:Console.log 返回 “string”user1809790 ,
这应该有效:

success: function(data) {
    if (data != '' && data !== null) { // Check if the data's not an empty string or null.
        $.each(data, function(i,item){
            if (item.Severity == 1) {
                // Do Something

关于php - 检查 JSON 的响应是否为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14067580/

相关文章:

PHP DOM - 访问新添加的节点

php - 如何解决性能问题?

php - Android 设备向 PHP 发送空数据

php - 如何组织模块化网络应用程序

javascript - 如何在 jquery 中检测 php 循环内单击了哪个按钮元素?

javascript - jQuery 如何区分 $() 和 $.method 调用?

PHP 防止直接访问

javascript - 在jquery循环中创建div元素

javascript - 为什么reduce的行为与手写的链式方法不同?

javascript - rails 2 : RJS - Javascript events are not working when on page updates remotely