如何在按下按钮时更新D3.js中的图形


How to update a graph in D3.js when pressing a button?

我正在绘制一张显示温度、日期和时间的图表。到目前为止,一切都很好,但为了从我的MySQL数据库中获得新值,需要完全刷新我的页面。我希望能够在不按"刷新"按钮的情况下更新图形。这是代码:

<?php require($_SERVER['DOCUMENT_ROOT'] . '/assets/php/getTemp.php' ); ?>
<!DOCTYPE html>
<meta charset="utf-8">
<head>
    <title>RPi</title>
</head>
<style>
div.tooltip {
    position: absolute;
    text-align: center;
    width: 120px;
    height: 28px;
    padding: 3px;
    font: 12px sans-serif;
    background: lightgrey;
    border: 0px;
    border-radius: 8px;
    pointer-events: none;
}

body { font: 14px Arial;}
path {
    stroke: #FF8C00;
    stroke-width: 3;
    fill: none;
}
.axis path,
.axis line {
    fill: none;
    stroke: black;
    stroke-width: 2;
    shape-rendering: crispEdges;
}
.grid .tick {
    stroke: grey;
    stroke-opacity: 0.3;
    shape-rendering: geometricPrecision;
}
.grid path {
          stroke-width: 0;
}

</style>
<body>

<div id="option">
    <input name="updateButton"
           type="button"
           value="Update"
           onclick="updateData()"
    />
</div>

<!-- load the d3.js library -->
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>

var margin = {top: 30, right: 20, bottom: 30, left: 50},
    width =  800 - margin.left - margin.right,
    height = 270 - margin.top - margin.bottom;
var parseDate = d3.time.format("%Y-%m-%d %H:%M:%S").parse;
var formatTime = d3.time.format("%d-%m-%Y %H:%M:%S");
var x = d3.time.scale().range([0, width]);
var y = d3.scale.linear().range([height, 0]);

var xAxis = d3.svg.axis().scale(x)
    .orient("bottom");
var yAxis = d3.svg.axis().scale(y)
    .orient("left").ticks(5);
var valueline = d3.svg.line()
    .interpolate("basis")
    .x(function(d) { return x(d.datetime); })
    .y(function(d) { return y(d.temperature); });
var div = d3.select("body").append("div")
    .attr("class", "tooltip")
    .style("opacity", 0);
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 + ")");
function make_x_axis() {
    return d3.svg.axis()
        .scale(x)
        .orient("bottom")
        .ticks(5)
}
function make_y_axis() {
     return d3.svg.axis()
        .scale(y)
        .orient("left")
        .ticks(5)
}
<?php echo "data=".$json_data.";" ?>
data.forEach(function(d) {
 d.datetime = parseDate(d.datetime);
 d.temperature = +d.temperature;
});
x.domain(d3.extent(data, function(d) { return d.datetime; }));
y.domain([0, d3.max(data, function(d) { return d.temperature; })]);

svg.append("path")
 .attr("class", "line")
 .attr("d", valueline(data));

svg.selectAll("dot")
    .data(data)
.enter().append("circle")
    .attr("r", 4)
    .attr("cx", function(d) { return x(d.datetime); })
    .attr("cy", function(d) { return y(d.temperature); })
    .on("mouseover", function(d) {
        div.transition()
             .duration(200)
             .style("opacity", 1);
        div.html(formatTime(d.datetime) + "<br/>" + d.temperature + " &#8451")
             .style("left", (d3.event.pageX + 16) + "px")
             .style("top", (d3.event.pageY + 16) + "px")
         .style("position", "absolute");
        })
     .on("mouseout", function(d) {
         div.transition()
            .duration(50)
            .style("opacity", 0);
});
svg.append("g")
  .attr("class", "grid")
  .attr("transform", "translate(0," + height + ")")
  .call(make_x_axis()
      .tickSize(-height, 0, 0)
      .tickFormat("")
)
svg.append("g")
  .attr("class", "grid")
  .call(make_y_axis()
      .tickSize(-width, 0, 0)
      .tickFormat("")
)
svg.append("g")
 .attr("class", "x axis")
 .attr("transform", "translate(0," + height + ")")
 .call(xAxis);
svg.append("g")
 .attr("class", "y axis")
 .call(yAxis);

</script>
</body>

我试着这样做:

function updateData() {
//d3.json("/assets/php/getTemp.php", function(error, data) {
        <?php echo "data=".$json_data.";" ?>
        data.forEach(function(d) {
        d3.select("body").selectAll("svg")
        d.datetime = parseDate(d.datetime);
        d.temperature = +d.temperature;
});
x.domain(d3.extent(data, function(d) { return d.datetime; }));
y.domain([0, d3.max(data, function(d) { return d.temperature; })]);
var svg = d3.select("body").transition();
    svg.select(".line") 
        .duration(750)
        .attr("d", valueline(data));
    svg.select(".x.axis")
        .duration(750)
        .call(xAxis);
    svg.select(".y.axis") 
        .duration(750)
        .call(yAxis);
};

但什么都没发生,甚至连一个错误都没有。

如果重要的话,这是用于从MySQL获取温度和时间的PHP代码:

<?php
$hostname = 'localhost';
$username = 'root';
$password = 'admin';
try {
    $dbh = new PDO("mysql:host=$hostname;dbname=temp_database",
                               $username, $password);

    $sth = $dbh->prepare("
       SELECT  `datetime`, `temperature` FROM  `tempLog`
    ");
    $sth->execute();

    $result = $sth->fetchAll(PDO::FETCH_ASSOC);

    $dbh = null;
}
catch(PDOException $e)
    {
        echo $e->getMessage();
    }
$json_data = json_encode($result);
?>

我需要做什么?

研究如何使用d3.json函数。这使您可以从php脚本中获得json,而无需从头开始重新加载整个页面。这是AJAX的东西,但是d3辅助函数隐藏了细节。

https://github.com/mbostock/d3/wiki/Requests

PS。请记住,这将是一个异步调用,因此也可以在此处查看已接受的答案:使用d3.JSON 从PHP输出JSON


至于为什么它目前不起作用,我的直觉是,尽管没有足够的信息来确认,但没有变化,因为它总是相同的数据,所以没有什么会改变

<?php echo "data=".$json_data.";" ?>

updateData中的^^^行在开始时求值一次,然后将整个函数放入javascript领域。无论您调用updateData多少次,如果不重新加载生成updateData的php页面,之前生成的javascript变量(data={some_json})都不会更改,即使您调用了生成服务器端变量的与数据库相关的php。

*这可能是无稽之谈,但行上方的位仍然是正确的