首页 > 解决方案 > 谷歌动态图表不使用 JSON 加载数据

问题描述

我正在尝试使用来自 MYSQL DB 的信息制作动态谷歌图表,我必须使用 json 页面从数据库中提取信息,而另一个应该使用该信息并创建图表

$query = "SELECT * FROM woodford_fuel";

$result = $conn->query($query);

$jsonArray = array();

if ($result->num_rows > 0) {
  while($row = $result->fetch_assoc()) {
    $jsonArrayItem = array();
    $jsonArrayItem['label'] = $row['reg'];
    $jsonArrayItem['value1'] = $row['consump_100'];
    array_push($jsonArray, $jsonArrayItem);
  }
}
$conn->close();
header('Content-type: application/json');
echo json_encode($jsonArray);

有了这个我得到以下结果,我得到的值是正确的

[{"label":"ND230819","value1":"50.55"},{"label":"ND866941","value1":"51.15"}]

我正在尝试使用以下脚本加载图表

function drawLineChart() {
    $.ajax({
      url: "chart_data.php",
      dataType: "json",
      type: "GET",
      contentType: "application/json; charset=utf-8",
      success: function (data) {
        var arrSales = [['label', 'value1']];    // Define an array and assign columns for the chart.

        // Loop through each data and populate the array.
        $.each(data, function (label, value1) {
          arrSales.push([value.label, value.value1]);
        });

        // Set chart Options.
        var options = {
          title: 'Average Consumption',
          curveType: 'function',
          legend: { position: 'bottom', textStyle: { color: '#555', fontSize: 14} }  // You can position the legend on 'top' or at the 'bottom'.
        };

        // Create DataTable and add the array to it.
        var figures = google.visualization.arrayToDataTable(arrSales)

        // Define the chart type (LineChart) and the container (a DIV in our case).
        var chart = new google.visualization.LineChart(document.getElementById('chart'));
        chart.draw(figures, options);      // Draw the chart with Options.
      },
      error: function (XMLHttpRequest, textStatus, errorThrown) {
        alert('Got an Error');
      }
    });
  }

它根本没有向我显示任何图表

标签: mysqljsonchartsgoogle-visualization

解决方案


推荐阅读