javascript - 对数据库中的 Google 图表感到困惑

标签 javascript json charts google-visualization

也许我问得更多,但我已经从 GoogleCharts 创建了一个简单的图表。 问题是我必须手动输入要从数据库填充的值。我知道有 JSON 可以做到这一点,但我已经浪费了 4 个小时的时间。 代码是:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title>
      Google Visualization API Sample
    </title>
    <script type="text/javascript" src="//www.google.com/jsapi"></script>
    <script type="text/javascript">
      google.load('visualization', '1', {packages: ['corechart']});
    </script>
    <script type="text/javascript">
      function drawVisualization() {
        // Create and populate the data table.
        var data = google.visualization.arrayToDataTable([
          ['x', 'Cats', 'Blanket 1', 'Blanket 2'],
          ['A',   1,       1,           0.5],
          ['B',   2,       0.5,         1],
          ['C',   4,       1,           0.5],
          ['D',   8,       0.5,         1],
          ['E',   7,       1,           0.5],
          ['F',   7,       0.5,         1],
          ['G',   8,       1,           0.5],
          ['H',   4,       0.5,         1],
          ['I',   2,       1,           0.5],
          ['J',   3.5,     0.5,         1],
          ['K',   3,       1,           0.5],
          ['L',   3.5,     0.5,         1],
          ['M',   1,       1,           0.5],
          ['N',   1,       0.5,         1]
        ]);

        // Create and draw the visualization.
        new google.visualization.LineChart(document.getElementById('visualization')).
            draw(data, {curveType: "function",
                        width: 500, height: 400,
                        vAxis: {maxValue: 10}}
                );
      }


      google.setOnLoadCallback(drawVisualization);
    </script>
  </head>
  <body style="font-family: Arial;border: 0 none;">
    <div id="visualization" style="width: 500px; height: 400px;"></div>
  </body>
</html>
​

现在我希望从数据库中获取数据,而不是手动写入。为此,我创建了一个 PHP 文件并从 MySQL DB 获取数据。

mysql_connect("localhost","root","");
mysql_select_db("db_graph");

$return_arr = array();
$fetch = mysql_query("SELECT * FROM tbl_graph"); 

感谢任何形式的帮助!

最佳答案

请至少使用 mysqli(或 PDO),而不是 mysql,因为它已被弃用。 http://us3.php.net/manual/en/mysqli.query.php

您需要为 API 提供一个“数组的数组”(数字索引,尽管在您到达 JS 层之前这并不重要)。并且,您必须提供列名称作为第一行:

<?php
$rows = array(
    array('Column 1', 'Column 2', 'Column 3'),
);

// Add the data
// With mysqli_query, the link argument is first and is required
$result = mysqli_query($conn, 'SELECT a, b, c FROM some_table');
while (($row = mysqli_fetch_array($result, MYSQLI_NUM)) {
    // should be array('column a value', 'column b value', 'column c value');
    $rows[] = $row;
}

// You can force the array to be numeric, but this should not be necessary
// because MYSQLI_NUM was used, and [] was used to append which means use
// numeric indices
// This is just more extra defensive coding if preferred
//foreach ($rows as $k => $v) {
//    $rows[$k] = array_values($v);
//}
//$rows = array_values($rows);

// Give the data to the front-end, with correct content type (assuming JSON here)
header('Content-Type: application/json');
print(json_encode($rows));

现在您需要获取该数据。我建议使用 AjAX 库,例如 jQuery。在您的 drawVisualization() 函数中:

$.getJSON('/some-endpoint/', function (data) {
    // Since this is the success callback, the data argument is your data from the server
    // Since $.getJSON() is used, there is no need to parse JSON here
    new google.visualization.LineChart(document.getElementById('visualization')).
        draw(data, {curveType: "function",
                        width: 500,
                        height: 400,
                        vAxis: {maxValue: 10}});
}).fail(function () { /* do something */ });

如果在每种情况下都无法使数组为数字,那么您将在某处获得带有对象的 JSON 流(例如: {'0': [1]} 而不是 [[1]])并且可视化将无法生成。

关于javascript - 对数据库中的 Google 图表感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23427933/

相关文章:

javascript - 当我尝试创建 Javascript 对象时未捕获引用错误

javascript - 即使将元素设置为自动,如何确定元素的 z-index

arrays - 将一维字符串数组转换为json文件

javascript - 简单的 d3.js 示例图表开始

javascript - D3-多放射状进度图

javascript - 如何使用 websockets 更改模板?

javascript - SAPUI5:如何在 HANA 中的两个表之间创建外键链接

python - 有没有办法让 Pyramid json 渲染器输出格式化的、 pretty-print 输出?

Json 操作 TypeScript Angular 2

iOS 图表 : Combined data into stacked bar chart?