我有一個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