链接到php文件的D3代码将实际代码作为文本输出到网页上


D3 code linking to php file outputs the actual code as text on the web page

我正试图使用d3代码输出一个简单的图,使用php从我的数据库中获得的日期和TCP上传信息。我可以正确地输出json数据,但每当我尝试运行html文件时,它都会将代码输出为文本,而根本没有图形。我试着寻找不同的解决方案,但似乎都不起作用。我甚至从aptana切换到使用cloud 9,似乎没有任何东西输出图形。我有一种感觉,它可能需要对d3代码或d3库的链接做些什么,但我完全迷失了方向。这是我的html代码:

 <!DOCTYPE html>
<meta charset="utf-8">
<html lang="en">
<style> /* set the CSS */
body { font: 12px Arial;}
path { 
    stroke: steelblue;
    stroke-width: 2;
    fill: none;
}
.axis path,
.axis line {
    fill: none;
    stroke: grey;
    stroke-width: 1;
    shape-rendering: crispEdges;
}
</style>
<body>
<!-- load the d3.js library -->    
<script src="http://d3js.org/d3.v3.min.js"></script>

// Set the dimensions of the canvas / graph
var margin = {top: 30, right: 20, bottom: 30, left: 50},
    width = 600 - margin.left - margin.right,
    height = 270 - margin.top - margin.bottom;
// Parse the date / time
var parseDate = d3.time.format("%d'/%b'/%y").parse;
// Set the ranges
var x = d3.time.scale().range([0, width]);
var y = d3.scale.linear().range([height, 0]);
// Define the axes
var xAxis = d3.svg.axis().scale(x)
.orient("bottom").ticks(5);
var yAxis = d3.svg.axis().scale(y)
    .orient("left").ticks(5);
// Define the line
var valueline = d3.svg.line()
.x(function(d) { return x(d.Date); })
.y(function(d) { return y(d.TCP_UP); });
// Adds the svg canvas
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 + ")");

   d3.json("capstone/connection.php", function(error, data) {
   data.forEach(function(d) {
    d.Date = parseDate(d.Date);
    d.TCP_UP = +d.TCP_UP;
});
// 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.TCP_UP; })]);
// Add the valueline path.
svg.append("path")
    .attr("class", "line")
    .attr("d", valueline(data));
// Add the X Axis
svg.append("g")
    .attr("class", "x axis")
    .attr("transform", "translate(0," + height + ")")
    .call(xAxis);
// Add the Y Axis
svg.append("g")
    .attr("class", "y axis")
    .call(yAxis);
//});
</script>
</body>
</html>

它基于这里的代码。

在这里发布的例子中,我只是想用我的php文件切换data.cvs文件,所以我不知道这是否也是一个问题。谢谢如果您需要更多信息,请告诉我。

好吧,您忘记打开脚本代码了。在代码和加载d3的脚本标记之间放置一个<script>标记。