只是d3js图表的初学者。我无法生成D3js图表。这是我的索引文件:
<!DOCTYPE html>
<html lang="en">
<meta charset="utf-8">
<style>
.arc text {
font: 10px sans-serif;
text-anchor: middle;
}
.arc path {
stroke: #fff;
}
</style>
<body>
<script src="d3/d3.min.js"></script>
<script>
var width = 600,
height = 600,
radius = Math.min(width, height) / 2;
var color = d3.scale.ordinal()
.range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"]);
var arc = d3.svg.arc()
.outerRadius(radius - 10)
.innerRadius(200);
var labelArc = d3.svg.arc()
.outerRadius(radius - 60)
.innerRadius(radius - 40);
var pie = d3.layout.pie()
.sort(null)
.value(function(d) { return d.population; });
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
d3.json("getdata.php", type, function(error, data) {
if (error) throw error;
var g = svg.selectAll(".arc")
.data(pie(data))
.enter().append("g")
.attr("class", "arc");
g.append("path")
.attr("d", arc)
.style("fill", function(d) { return color(d.data.age); });
g.append("text")
.attr("transform", function(d) { return "translate(" + labelArc.centroid(d) + ")"; })
.attr("dy", ".35em")
.text(function(d) { return d.data.age; });
});
function type(d) {
d.population = +d.population;
return d;
}
</script>
</body>
</html>
这里我从php获取数据,getdata.php:
<?php
$conn = mysqli_connect("localhost","root","","androidtest");
$query = "SELECT * FROM charts";
$result = mysqli_query($conn, $query);
$rows = mysqli_num_rows($result);
mysqli_close($conn);
if($rows > 0){
$data = array();
while (($r=mysqli_fetch_assoc($result))!=null){
$data[] = $r;
}
header("Content-Type: application/json");
echo json_encode($data);
}
?>
我的数据库如下所示,表名图表
-------------------------------
| age | population |
-------------------------------
| <5 | 2704659 |
| 5-13 | 4499890 |
| 4-17 | 2159981 |
|18-24 | 3853788 |
|25-44 | 14106543 |
|46-64 | 8819342 |
| >65 | 612463 |
-------------------------------
在运行index.php文件时,检查窗口中的Javascript没有错误。它显得空白。
在调用d3.json之后(&#34; getdata.php&#34; ...我尝试将结果发送到控制台日志,例如:
console.log(JSON.stringify(data));
console.log("Testing");
没有控制台日志。 BLANK。
我也运行:getdata.php,它返回字符串:
[{"age":"<5","population":"2704659"},{"age":"5-13","population":"4499890"},{"age":"14-17","population":"2159981"},{"age":"18-24","population":"3853788"},{"age":"25-44","population":"14106543"},{"age":"46-64","population":"8819342"},{"age":">65","population":"612463"}]