使用传递的JSON数组创建Google折线图

时间:2019-03-28 00:50:32

标签: javascript json ajax datetime google-visualization

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

我尝试使用arrayToDataTable()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']});,并且同一页面上还有其他工作图表。

1 个答案:

答案 0 :(得分:1)

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

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

最重要的是,在javascript中,使用此特定的日期构造函数时,
该月从零开始,表示-> January = 0

这样,上述日期将是4月26日。,我想您要 3月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)

中将其转换为datetime

接下来,图表希望每个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>