首页 > 解决方案 > 使用传递的 JSON 数组创建 Google 折线图

问题描述

我有一个通过 ajax 传递的 JSON 数组,并且在绘制数据图表时遇到了问题。我需要能够将数组传递给图表,动态添加不重复的列。

我尝试使用然后使用arrayToDataTable()and但是每次错误传递不同的值。DataTable()data.addColumns()data.addRow()

ajax 调用被触发:

$.ajax({
    type: "POST",
    url: "/file.php",
    data: {
        data: dataHere,
    },
    dataType: "JSON",
    success: function(result) {
        var div = mydiv;
        drawInterfaceChart(result,div);
    },
});

从 PHP 编码的 JSON 使用:

$SQL = "SELECT DATE_FORMAT(date, 'new Date(%Y, %c, %d, %H, %i, %s)') as date, ifDesc, ifInOctets FROM tablename WHERE date between (CURDATE() - INTERVAL 1 MONTH ) and CURDATE()";
$Results = mysqli_query($db, $SQL) or die("Mysql cannot run Query");
$SQLRows = mysqli_num_rows($Results);
if ($SQLRows > 0) {
    $rows = array();
    while ($row = MySQLi_fetch_assoc($Results)) {
        $rows[] = $row;
    }
    echo json_encode($rows);
}

传递的 JSON 数组示例:

0: {date: "new Date(2019, 3, 26, 16, 13, 15)", ifDesc: "lo", ifInOctets: "2147483647"}
1: {date: "new Date(2019, 3, 26, 16, 13, 15)", ifDesc: "Port1", ifInOctets: "2147483647"}
2: {date: "new Date(2019, 3, 26, 16, 13, 15)", ifDesc: "Port2", ifInOctets: "2147483647"}
3: {date: "new Date(2019, 3, 26, 16, 13, 16)", ifDesc: "Port6", ifInOctets: "2147483647"}
4: {date: "new Date(2019, 3, 26, 16, 13, 16)", ifDesc: "imq0", ifInOctets: "906413834"}
5: {date: "new Date(2019, 3, 26, 16, 17, 31)", ifDesc: "lo", ifInOctets: "2147483647"}
6: {date: "new Date(2019, 3, 26, 16, 17, 49)", ifDesc: "Port1", ifInOctets: "2147483647"}
7: {date: "new Date(2019, 3, 26, 16, 17, 53)", ifDesc: "Port2", ifInOctets: "171330279"}
8: {date: "new Date(2019, 3, 26, 16, 17, 57)", ifDesc: "Port6", ifInOctets: "2147483647"}
9: {date: "new Date(2019, 3, 26, 16, 17, 57)", ifDesc: "imq0", ifInOctets: "1103910085"}
10: {date: "new Date(2019, 3, 26, 16, 20, 38)", ifDesc: "lo", ifInOctets: "2147483647"}
11: {date: "new Date(2019, 3, 26, 16, 20, 39)", ifDesc: "Port1", ifInOctets: "2147483647"}
12: {date: "new Date(2019, 3, 26, 16, 20, 40)", ifDesc: "Port2", ifInOctets: "194386054"}
13: {date: "new Date(2019, 3, 26, 16, 20, 41)", ifDesc: "Port6", ifInOctets: "2147483647"}
14: {date: "new Date(2019, 3, 26, 16, 20, 42)", ifDesc: "imq0", ifInOctets: "1128562685"}

我的绘制图表功能:

function drawInterfaceChart(array,divR) {
    var dataSet = [];
    $.each(array, function (data, value) {
        dataSet.push([value.date, value.ifDesc, value.ifInOctets]);
    });
    var data = google.visualization.arrayToDataTable(dataSet);
    var chart = new google.visualization.LineChart(document.getElementById(divR));
    var options = {
        title: '',
        legend: { position: 'right' }
    };
    chart.draw(data, options);
}

此布局返回错误:轴 #0 的数据列不能是字符串类型

第 0 列需要是一个日期时间,每列显示一个折线图,它是每个“ifDesc”值的数据。我希望在图表中添加更多数据,因此创建列需要是动态的。

提前致谢!

编辑:

我忘了提到我的页面确实包括:google.charts.load('current', {'packages':['corechart', 'gauge']});并且我在同一页面上有其他工作图表。

标签: javascriptjsonajaxdatetimegoogle-visualization

解决方案


这里有几个问题,首先是日期。

"new Date(2019, 3, 26, 16, 13, 15)"
如果不使用eval我不推荐的方法, 您将无法从此字符串中获取实际的日期时间--> 。

最重要的是,在 javascript 中,当使用这个特定的日期构造函数时,
月份是从零开始的,这意味着 -->January = 0

因此,上述日期将导致April 26,我想你想要March 26

这是证明(运行以下代码段)...

var testDate = eval("new Date(2019, 3, 26, 16, 13, 15)");
console.log(testDate);

建议将格式更改为 -->3/26/2019 16:13:15
{date: "3/26/2019 16:13:15", ifDesc: "lo", ifInOctets: "2147483647"}
然后在 javascript 中转换为日期时间 -->new Date(value.date)


接下来,图表期望每个都ifDesc在数据表中自己的列中,
如下面的结构......

['Date', 'lo', 'Port1', 'Port2', 'Port6', 'img0'],
[new Date('3/26/2019 16:13:15'), 2147483647, 2147483647, 2147483647, 2147483647, 906413834],

如果没有硬编码,这将很难在查询中构建。

相反,我们可以使用 google 的数据视图来创建所需的结构。

在以下结构中通过 ajax 传递 json。

{date: "3/26/2019 16:13:15", ifDesc: "lo", ifInOctets: "2147483647"}

加载类似于您所做的数据表,
我们需要转换日期并解析数字...

var dataSet = [];
$.each(array, function (data, value) {
    dataSet.push([new Date(value.date), value.ifDesc, parseFloat(value.ifInOctets)]);
});
var data = google.visualization.arrayToDataTable(dataSet);

然后使用以下内容为折线图创建数据视图。
它首先为每个ifDesc.

var viewColumns = [0];
var distinctLabels = data.getDistinctValues(1);
$.each(distinctLabels, function (index, label) {
  viewColumns.push({
    calc: function (dt, row) {
      if (dt.getValue(row, 1) === label) {
        return dt.getValue(row, 2);
      }
      return null;
    },
    type: 'number',
    label: label
  });
});
var view = new google.visualization.DataView(data);
view.setColumns(viewColumns);

请参阅以下工作片段...

google.charts.load('current', {
  packages:['corechart']
}).then(function () {
  var jsonData = [
    {date: "3/26/2019 16:13:15", ifDesc: "lo", ifInOctets: "2147483647"},
    {date: "3/26/2019 16:13:15", ifDesc: "Port1", ifInOctets: "2147483647"},
    {date: "3/26/2019 16:13:15", ifDesc: "Port2", ifInOctets: "2147483647"},
    {date: "3/26/2019 16:13:16", ifDesc: "Port6", ifInOctets: "2147483647"},
    {date: "3/26/2019 16:13:16", ifDesc: "imq0", ifInOctets: "906413834"},
    {date: "3/26/2019 16:17:31", ifDesc: "lo", ifInOctets: "2147483647"},
    {date: "3/26/2019 16:17:49", ifDesc: "Port1", ifInOctets: "2147483647"},
    {date: "3/26/2019 16:17:53", ifDesc: "Port2", ifInOctets: "171330279"},
    {date: "3/26/2019 16:17:57", ifDesc: "Port6", ifInOctets: "2147483647"},
    {date: "3/26/2019 16:17:57", ifDesc: "imq0", ifInOctets: "1103910085"},
    {date: "3/26/2019 16:20:38", ifDesc: "lo", ifInOctets: "2147483647"},
    {date: "3/26/2019 16:20:39", ifDesc: "Port1", ifInOctets: "2147483647"},
    {date: "3/26/2019 16:20:40", ifDesc: "Port2", ifInOctets: "194386054"},
    {date: "3/26/2019 16:20:41", ifDesc: "Port6", ifInOctets: "2147483647"},
    {date: "3/26/2019 16:20:42", ifDesc: "imq0", ifInOctets: "1128562685"}
  ];

  drawInterfaceChart(jsonData, 'chart_div');

  function drawInterfaceChart(array, divR) {
    var dataSet = [];
    $.each(array, function (data, value) {
      dataSet.push([new Date(value.date), value.ifDesc, parseFloat(value.ifInOctets)]);
    });
    var data = google.visualization.arrayToDataTable(dataSet, true);

    var viewColumns = [0];
    var distinctLabels = data.getDistinctValues(1);
    $.each(distinctLabels, function (index, label) {
      viewColumns.push({
        calc: function (dt, row) {
          if (dt.getValue(row, 1) === label) {
            return dt.getValue(row, 2);
          }
          return null;
        },
        type: 'number',
        label: label
      });
    });
    var view = new google.visualization.DataView(data);
    view.setColumns(viewColumns);

    var chart = new google.visualization.LineChart(document.getElementById(divR));
    var options = {
      title: '',
      legend: {position: 'right'},
      interpolateNulls: true  // <-- add this option
    };
    chart.draw(view, options);  // <-- use view to draw chart
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>


推荐阅读