0

我正在尝试做一些基本的谷歌图表,由数据库通过 PHP/PDO/MSSQL 填充,通过 AJAX 传递给 .js

我有一个非常基本的问题,我觉得是编码。

我正在关注教程https://developers-dot-devsite-v2-prod.appspot.com/chart/interactive/docs/gallery/linechart

他们将数据硬编码到谷歌图表中,但我通过 Ajax 发送我的数据。我来自 Ajax 的数据如下所示:

$data = "['Year', 'Sales', 'Expenses'],['2004',  1000,      400],['2005',  1170,      460], ['2006',  660,       1120],['2007',  1030,      540]";
       
echo (json_encode($data));

resulting in:
"['Year', 'Sales', 'Expenses'],['2004', 1000, 400],['2005', 1170, 460], ['2006', 660, 1120],['2007', 1030, 540]"

但是,当我运行图表时,我收到错误“错误:arrayToDataTable 的数据不是数组”。

我通过 AJAX 逐字发送完全相同的数据,所以我错过了什么?

而不是谷歌示例:

 function drawChart() {
        var data = google.visualization.arrayToDataTable([
          ['Year', 'Sales', 'Expenses'],
          ['2004',  1000,      400],
          ['2005',  1170,      460],
          ['2006',  660,       1120],
          ['2007',  1030,      540]
        ]);

        var options = {
          title: 'Company Performance',
          curveType: 'function',
          legend: { position: 'bottom' }
        };

        var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));

我在用着:

function drawChart() {

          var jsonData = $.ajax({
            url: "reports/GoogleCharts/ajax_StationExpenses.php",
            dataType: "json"
          }).responseText;
 

       var data = new google.visualization.arrayToDataTable(jsonData);
        
       var options = {
          title: 'Station Utility Expense Over $250 by Month',
          curveType: 'function',
          legend: { position: 'bottom' },
          width: 800,
          height: 600,
          animation:{ startup: true, duration: 1700, easing: 'in' }
        };

        var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
        chart.draw(data, options);
}

我错过了什么,为什么它需要硬编码,而不是看起来与 AJAX 从我的 php 页面推送的完全相同的格式?

4

1 回答 1

0

您的 $data 值是一个字符串,而不是一个数组。

$data = "anything here"; //a string
$data = "[['also','a','string'],...]"; //also a string

JSON 编码字符串不会产生有效的 JSON。

$data = array(
    array("Year","Sales","Expenses"),
    array("2004",1000,400),
    array("2005",1170,460),
    array("2006",660,1120),
    array("2007",1030,540)
);

以上是一个有效的 PHP 数组。

$data = [
    ["Year","Sales","Expenses"],
    ["2004",1000,400],
    ["2005",1170,460],
    ["2006",660,1120],
    ["2007",1030,540]
]; 

.. 当然,您也可以使用 PHP 速记来编写数组。

$json = json_encode($data);

以上是一个有效的 JSON 编码数组。

添加 JSON 标头:

header('Content-type: application/json');
exit( $json );
于 2021-06-11T21:33:29.217 回答