我有一个HTML文件中像这样:如何阅读和情节JSON与chart.js之
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.6/Chart.min.js"></script>
<script src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
</head>
<body>
<canvas id="myChart" width="400" height="400"></canvas>
<script>
function drawChart() {
console.log("start");
$.getJSON("test.json", function (data) {
console.log("loaded");
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'bar',
data: data,
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
}).fail(function(){
console.log("fail")
});
}
drawChart()
</script>
</body>
</html>
...和JSON文件是这样的:
{
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [20, 19, 3, 5, 2, 3],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
}
...和json加载总是失败。 我尝试了几种方法来读取json并使用Chart.js绘制图表,但总是失败。
我试图绘制用PHP JSON没有成功:
<?php
header("Content-Type: application/json");
$filename = "test.json";
$fp = fopen($filename, "r");
$content = fread($fp, filesize($filename));
explode("\n", $content);
fclose($fp);
print_r($content);
?>
这有什么错呢?
感谢丹尼尔的PHP! JS对我来说绝对是新的,所以我寻找完全不同的问题。 – yoman