首页 > 解决方案 > 使用 json 从 mysql 获取数据并使用 D3 绘图

问题描述

我正在尝试用 d3 绘制 mysql 数据。我正在使用 php 转换为 json 格式。出于测试目的,我按照此处的步骤并在 XAMPP 上使用了我自己的 php 文件。但是当我在浏览器中打开 html 文件时,它总是显示一个白页。

<?php
$mysqli  = mysqli_connect("$host, $username, $password, $dbname");
$mysqli ->set_charset('utf8mb4');
$myArray = array();
 
if($result = $mysqli ->query("SELECT  `date`, `volume` FROM  `sensordata`"))
{
    while ($row = $result->fetch_array(MYSQLI_ASSOC)) 
    {
    $myArray[] = $row;
    }
    header("Content-Type: application/json");
    echo json_encode($myArray);
}
$result->close();
$mysqli ->close();
?>

它以 json 格式回显,如下所示:

[{“日期”:“02-04-2021”,“音量”:“606.51”},{“日期”:“03-04-2021”,“音量”:“700.51”}]

我使用网站上的以下代码:

<!DOCTYPE html>
<meta charset="utf-8">
<html lang = "en">
    <style> /* set the CSS */

    .line {
      fill: none;
      stroke: steelblue;
      stroke-width: 2px;
    }
    
    </style>

<body>
<script src="d3/d3.js"></script>
    
<script>
// set the dimensions and margins of the graph
  var margin = {top: 20, right: 20, bottom: 30, left: 50},
      width = 960 - margin.left - margin.right,
      height = 500 - margin.top - margin.bottom;

// parse the date / time
  var parseTime = d3.timeParse("%d-%m-%Y");

// set the ranges
  var x = d3.scaleTime().range([0, width]);
  var y = d3.scaleLinear().range([height, 0]);

// define the line
  var valueline = d3.line()
    .x(function(d) { return x(d.date); })
    .y(function(d) { return y(d.volume); });

// append the svg obgect to the body of the page
// appends a 'group' element to 'svg'
// moves the 'group' element to the top left margin
  var svg = d3.select("body").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
    .append("g")
    .attr("transform","translate(" + margin.left + "," + margin.top + ")");

// Get the data
d3.json("get_data.json", function(error, data) {
  if (error) throw error;

  // format the data
  data.forEach(function(d) {
      d.date = parseTime(d.date);
      d.volume = +d.volume;
  });

  // Scale the range of the data
  x.domain(d3.extent(data, function(d) { return d.date; }));
  y.domain([0, d3.max(data, function(d) { return d.volume; })]);

  // Add the valueline path.
  svg.append("path")
      .data([data])
      .attr("class", "line")
      .attr("d", valueline);

  // Add the X Axis
  svg.append("g")
      .attr("transform", "translate(0," + height + ")")
      .call(d3.axisBottom(x)
      .tickFormat(d3.timeFormat("%d-%m-%Y")));
  // Add the Y Axis
  svg.append("g")
      .call(d3.axisLeft(y));

});
  </script>
</body>

如果我使用这样的变量:

var data = [
    {date:"30-05-12",volume:"123"},
    {date:"27-05-12",volume:"67.00"},
    {date:"26-06-12",volume:"89.70"},
    {date:"25-07-12",volume:"99.00"}
];

而不是这部分:

// Get the data
d3.json("get_data.json", function(error, data) {
  if (error) throw error;

  // format the data
  data.forEach(function(d) {
      d.date = parseTime(d.date);
      d.volume = +d.volume;
  });

一切都很好,数据被绘制出来。

所有文件都在同一个文件夹中。

有人可以帮我吗?

标签: javascriptphpjsond3.js

解决方案


您在此处请求 JSON 文件,而不是您的 PHP 文件:

d3.json("get_data.json", ...)

因此,您可能想要请求您的 PHP 文件,或者提前将 JSON 数据写入 *.json 文件:

if($result = $mysqli ->query("SELECT  `date`, `volume` FROM  `sensordata`"))
{
    ...
    file_put_contents('get_data.json', json_encode($myArray));
}

此外,您提供的 PHP 输出和硬编码的日期格式不同(“02-04-2021”与“30-05-12”)。如果您喜欢使用后者,您可能需要调整代码的日期格式字符串(假设 d3.js 也使用它来解析日期):

var parseTime = d3.timeParse("%d-%m-%y")

对于 d3.json(),另见他们的文档


推荐阅读