2016-07-23 29 views
0

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

這有什麼錯呢?

回答

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 
    }] 
} 
+0

感謝丹尼爾的PHP! JS對我來說絕對是新的,所以我尋找完全不同的問題。 – yoman

0

請改變你的PHP來:

<?php 
header("Content-Type: application/json"); 
echo file_get_contents("test.json"); 
+0

謝謝你的提醒它沒有解決原來的問題,但簡化了我的PHP文件 – yoman