我有一个像这样的html文件:
var value = "red"
var obj1 = {value: "foo"} // {value: "foo"}
var obj2 = {color: value} // {color: "red"}
var obj3 = {[value]: "foo"} // {red: "foo"}
...和这样的json文件:
<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加载总是失败。 我尝试了几种方法来读取json并使用Chart.js绘制图表,但总是失败。
我试图用php绘制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
}]
}
这有什么问题?
答案 0 :(得分:0)
请将您的PHP更改为:
<?php
header("Content-Type: application/json");
echo file_get_contents("test.json");
答案 1 :(得分:0)
问题在于JSON文件。你应该使用引号(“)。
这是正确的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
}]
}