[英]Using JSON file data in Chart.js
pretty new to javascript. javascript新手。 Im trying to read a JSON file located on my localhost ( http://localhost:8080/jsonData.json ) and format it to be displayed using Chart.js.
我试图读取位于我的本地主机( http:// localhost:8080 / jsonData.json )上的JSON文件,并将其格式化为使用Chart.js显示。
Here is my JSON File: 这是我的JSON文件:
[{"date": "1/02/16", "price":15.25},
{"date":"29/01/16", "price":15.35},
{"date":"28/01/16", "price":15.1}]
and my html file which will display the chart: 和我的HTML文件将显示图表:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Test Chart</title>
<script src="javascript/Chart.js"></script>
</head>
<body>
<canvas id="mycanvas" width="400" height="400"></canvas>
<script>
$.getJSON( "http://localhost:8080/jsonData.json", function( data ) {
var chartjsData = [];
var labels = [];
$.each( data, function( key, val ) {
labels.push(key);
chartjsData.push(val);
});
var lineChartData = {
labels : labels,
datasets : [{
fillColor : "rgba(220,280,220,0.5)",
strokeColor : "rgba(220,220,220,1)",
data : chartjsData
}]
};
var myLine = new Chart(document.getElementById("mycanvas").getContext("2d")).Line(lineChartData);
});
</script>
</body>
</html>
basically when i run it i just get a blank screen with nothing displayed so I'm guessing its something to do with how I'm parsing the file, any help would be appreciated. 基本上,当我运行它时,我只是得到一个空白屏幕,什么都没有显示,因此我猜测它与解析文件的方式有关,任何帮助将不胜感激。
The JSON in that txt file is not a valid JSON object. 该txt文件中的JSON不是有效的JSON对象。 You need to use regular quotes like so:
您需要像这样使用常规引号:
[{"date": "1/02/16", "price":15.25},
{"date":"29/01/16", "price":15.35},
{"date":"28/01/16", "price":15.1}];
Also you can use jQuery's $.getJSON
function here: 您也可以在此处使用jQuery的
$.getJSON
函数:
var myJSON = $.getJSON( "example.json", function() {
console.log( "success" );
})
see here: http://api.jquery.com/jquery.getjson/ 看到这里: http : //api.jquery.com/jquery.getjson/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.