Google Chart API在折线图上无效的JSON字符串

时间:2016-04-17 10:08:45

标签: php mysql json datetime google-visualization

我正在尝试使用Google Charts API创建基于MySQL数据库的折线图。数据库包含温度和时间戳。

我有getData.php来获取数据并将其转换为JSON。

<?php
$servername = "xxx";
$username = "xxx";
$password = "xxx";
$dbname = "xxx";


$conn = mysqli_connect($servername, $username, $password, $dbname);

// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

$qry = "SELECT * FROM temp";

$result = mysqli_query($conn,$qry);

$table = array();
$table['cols'] = array(

    array('label' => 'Time', 'type' => 'datetime'),
    array('label' => 'Temperature', 'type' => 'number')
);

$rows = array();
foreach($result as $row){

    $temp = array();

    //$temp[] = array('v' => 'Date(' . $row['time'] . ')'); OLD

    //turn timestamps into correct datetime form Date(Y,n,d,H,i,s) 
    $temp[] = array('v' => 'Date('.date('Y',strtotime($row['time'])).',' . 
                                 (date('n',strtotime($row['time'])) - 1).','.
                                 date('d',strtotime($row['time'])).','.
                                 date('H',strtotime($row['time'])).','.
                                 date('i',strtotime($row['time'])).','.
                                 date('s',strtotime($row['time'])).')'); 


    $temp[] = array('v' => (float) $row['temperature']); 
    $rows[] = array('c' => $temp);
}

$table['rows'] = $rows;

$jsonTable = json_encode($table, true);
echo $jsonTable;    
?>

时间戳根据Google的说明转换为“日期(年,月,日,小时,分钟,秒,毫秒)”格式:https://developers.google.com/chart/interactive/docs/datesandtimes#dates-times-and-timezones

这是我的main.html。它基于Google的示例(https://developers.google.com/chart/interactive/docs/php_example#exampleusingphphtml-file

<html>
<head>
    <!--Load the AJAX API-->
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script type="text/javascript">

      // Load the Visualization API and the corechart package.
        google.charts.load('current', {'packages':['line']});

      google.charts.setOnLoadCallback(drawChart);

      function drawChart() {

        var jsonData = $.ajax({
          url: "getData.php",
          dataType: "json",
          async: false
          }).responseText;

        var data = new google.visualization.DataTable(jsonData); //Line 27


        var options = {'title':'Temperature',
                       'width':720,
                       'height':480};

        var chart = new google.charts.Line(document.getElementById('chart_div'));


        //chart.draw(data, options);
        //chart.draw(data, {width: 400, height: 240});
        chart.draw(data, google.charts.Line.convertOptions(options));



      }
    </script>

</head>

<body>
   <div id="chart_div"><p id="test"></p></div>
</body>
<html>

该网站为空,Chrome调试器显示此错误:

未捕获错误:无效的JSON字符串:

<body>
{"cols":[{"label":"Time","type":"datetime"},{"label":"Temperature","type":"number"}],"rows":[{"c":[{"v":"Date(2016,3,14,10,36,30)"},{"v":22}]},{"c":[{"v":"Date(2016,3,14,10,37,31)"},{"v":25}]},{"c":[{"v":"Date(2016,3,14,10,37,53)"},{"v":21}]},{"c":[{"v":"Date(2016,3,15,01,23,37)"},{"v":21}]}]}
</body>

yl @ VM1981:170
Ol @ VM1981:174
Sp @ VM1981:234
drawChart @ main.html:27
google.a.b.Na @ loader.js:147
g @ loader.js:145

main.html:27是var data = new google.visualization.DataTable(jsonData);线。

这是使用jsonlint格式化的JSON

{
"cols": [{
    "label": "Time",
    "type": "datetime"
}, {
    "label": "Temperature",
    "type": "number"
}],
"rows": [{
    "c": [{
        "v": "Date(2016,3,14,10,36,30)"
    }, {
        "v": 22
    }]
}, {
    "c": [{
        "v": "Date(2016,3,14,10,37,31)"
    }, {
        "v": 25
    }]
}, {
    "c": [{
        "v": "Date(2016,3,14,10,37,53)"
    }, {
        "v": 21
    }]
}, {
    "c": [{
        "v": "Date(2016,3,15,01,23,37)"
    }, {
        "v": 21
    }]
}]
}

我在这里完全不知所措。 JSON字符串应该没问题,它也由jsonlint.com验证。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

复制代码并在getData.php中返回粘贴的json字符串我无法重现您的错误。

请检查main.html中的ajax响应:

console.log(jsonData);

如果我在getData.php中添加额外的输出(例如var_dump something),我可以创建无效的JSON字符串错误。在

<body>
但是,您的JSON字符串周围的

标记是可疑的,因为在错误消息中打印了格式错误的JSON字符串,因此标记似乎是您的JSON字符串的一部分。你的php代码是否在getData.php中嵌入了body-tags?

在main.html中你可以尝试:

jsonData=jsonData.replace("<body>", "").replace("</body>", "");

检查,如果这可能是问题。