【问题标题】:Google Chart API invalid JSON string on Line Chart折线图上的 Google Chart API 无效 JSON 字符串
【发布时间】:2016-08-09 01:57:01
【问题描述】:

我正在尝试使用 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 验证。任何帮助将不胜感激。

【问题讨论】:

  • 关于您删除的评论:数据点非常接近,轴标签没有那么有用。您可以编辑格式: var options = {'title':'Temperature', 'width':720, 'height':480, 'hAxis':{'format': 'dd/MM/yyyy HH:mm'} };
  • 再次感谢,我设法找到了自己并且无法编辑评论,因此决定将其删除。答案是从 getData.php 中删除 标记。非常感谢您的回答。我现在实际上正在考虑如何在图表中的每个点上获得 X 轴上的时间戳。这是图表的图片。当前数字仅用于测试。 puu.sh/olQh0/8307ba8a9c.png
  • 这似乎是连续图表的问题。如果水平轴不需要根据时间缩放,那么您可以通过从日期时间类型切换到字符串并将时间戳格式化为字符串来切换到离散图表。否则我不知道解决方案,也许打开另一个问题?

标签: php mysql json datetime google-visualization


【解决方案1】:

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

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

console.log(jsonData);

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

<body>

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

在 main.html 你可以试试:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    • 2011-08-25
    • 1970-01-01
    相关资源
    最近更新 更多