【问题标题】:jQuery Ajax Json response - check if is nulljQuery Ajax Json 响应 - 检查是否为空
【发布时间】:2015-12-24 18:44:13
【问题描述】:

我正在使用 jQuery Ajax 和 JSON 从 MySQL 获取数据。但是我需要知道响应何时为空。我将一个日期参数传递给我的 php,它将返回一些数据或不返回...取决于日期。

我的 Javascript 代码(简单版):

function pac_irra(date){
    .ajax({
            url: 'get_db_data/pac_irra.php?date='+date,
            dataType: 'JSON',
            type: 'POST',
            data: {get_values: true},
            beforeSend: function(){
            $("#morris-line-chart").append(load_img);
            },
            success: function(response) {

                date =  response[0].Timestamp;
                $('#a1').append(date);
            },
        });
    }

例如,如果我使用了昨天 (2015-09-26) 的数据,我会得到以下 json 数据(只是其中的一部分):

[{"Timestamp":"2015-09-26 16:50:00","pac":"35.20","irra":"38.97"},{"Timestamp":"2015-09-26 17:00:00","pac":"32.19","irra":"35.51"}]

现在,例如,如果我选择了一个没有返回数据的日期:

[]

在下面的 javascript 代码中,我想在我的成功函数中添加一个 if 语句,以防 json 数组为空...类似于:

 function pac_irra(date){
        .ajax({
                url: 'get_db_data/pac_irra.php?date='+date,
                dataType: 'JSON',
                type: 'POST',
                data: {get_values: true},
                beforeSend: function(){
                $("#morris-line-chart").append(load_img);
                },
                success: function(response) {
                    date =  response[0].Timestamp;
                    $('#a1').append(date);
                 if ( ***array is empty***) {
                         ('#a1').append('No data');
                    };
                },
            });
        }

在我的成功函数中,我有一个使用 json 数据创建的莫里斯图...我没有把它放在代码中...

那么我如何检查它是否为空?我已经做了很多尝试:

if (response.length == 0) 

或其他尝试

if (response[0].Timestamp == "") or if (!response)

没有任何效果...我仍然无法检查 json 数组是否为空...

我的php代码:

<?php
    error_reporting(0);
    $path = $_SERVER['DOCUMENT_ROOT'];
    $path .= "/database/db_connect.php";
    include_once($path);
    if(isset($_GET['date'])) {
    $date = $_GET['date'];
    $days = $_GET['days'];      

        $var = array();  
        $query = "SELECT CONVERT_TZ(CONCAT(Date,' ',pac.Time), 'UTC', 'Europe/Lisbon' ) as Timestamp, ROUND((pac.Value/6440)*100,2) pac, ROUND((irra.Value/1000)*100,2) irra
        FROM AggData pac
        LEFT JOIN (SELECT Time, Value 
        FROM AggData WHERE Date=DATE_ADD('$date',INTERVAL '$days' DAY) and idEquipment=5 and idMeasure=6 ) irra 
        ON pac.Time=irra.Time 
        Where pac.Date=DATE_ADD('$date',INTERVAL '$days' DAY) and pac.idEquipment=1 and pac.idMeasure=3
        AND (irra.Value>0 or pac.Value>0)
        Order BY pac.Time asc
        " or die("Error in the consult.." . mysqli_error($link)); 
        $result = $link->query($query); 
        while($obj = mysqli_fetch_object($result)) {
            $var[] = $obj;
        }
    echo json_encode($var);
}
?>

【问题讨论】:

  • 你可以使用 response.length == 0
  • var rep = JSON.parse(response); if(rep != null || rep == "")
  • aldrin27 不起作用 :(
  • 为什么不在后端发送响应之前检查查询结果是否为空?然后返回一个字符串“No result Found”,如果它是 null 以及一个状态错误。

标签: php jquery mysql json ajax


【解决方案1】:

试试下面是否会检查各种情况

   if((response && jQuery.isArray(response))?(response.length==0?false:(jQuery.isPlainObject(response[0])?!jQuery.isEmptyObject(response[0]):response[0])):response){

       //console.log("adfdsaf");
    }

如果它会检查是否 响应为空或未定义 或响应 == [] 或响应 == [{}] 或响应[""]

我认为这是问题

    success: function(response) {
             if((response && jQuery.isArray(response))?(response.length==0?false:(jQuery.isPlainObject(response[0])?!jQuery.isEmptyObject(response[0]):response[0])):response){
                   ('#a1').append('No data');
               }else{
                   date =  response[0].Timestamp;
                   $('#a1').append(date);

                }  
                };
            },

希望它会起作用

【讨论】:

  • 我已经尝试过你的代码......但没有任何反应 if((response && jQuery.isArray(response))?(response.length==0?false:(jQuery.isPlainObject(response[ 0])?!jQuery.isEmptyObject(response[0]):response[0])):response){ if (response == [] || response == [{}] || response[""]) { $('#chart_title').append('没有数据!'); };
  • 你能把你收到的回复发给我吗?只需使用 console.log(response) 打印它。也许您在字符串中以这种格式“[]”得到响应。如果你发给我,这将是 gr8 帮助解决它。谢谢
  • 发现问题.. function(response) { date = response[0].Timestamp; $('#a1').append(date); if ( array is empty) ........ 因为我们没有检查 response 是 undefined 还是 null.. 并试图检索 Timestamp.. response [0].时间戳..
  • 我已经更新了答案,请检查一下,因为我们试图在成功块中检索响应[0].Timestamp,而不检查响应是否为空,这就是为什么我们出现错误
猜你喜欢
  • 2012-12-13
  • 1970-01-01
  • 2019-01-23
  • 1970-01-01
  • 2021-08-12
  • 2020-08-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多