[英]How do I display chart on my HTML page based on JSON data sent by Node JS
I wish to display my JSON data on client side HTML/JS which is fetched from server side NodeJS API in the form of a chart using chartjs or D3.js
(or anything which seems relevant).我希望在客户端 HTML/JS 上显示我的 JSON 数据,这些数据是从服务器端 NodeJS API 以图表的形式使用chartjs或D3.js
的(或任何似乎相关的内容)。
Here is my index.html
这是我的index.html
<script
src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<canvas id="chart" height="400px" width="400px"></canvas>
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
url: 'http://localhost:8050/api/opcounterTest',
type: 'POST',
dataType: 'json',
success: function (res) {
console.log(res);
divData = '';
var myLabels = [];
var myData = [];
$.each(res, function (key, value) {
console.log(key);
console.log(value);
myLabels.push(key);
myData.push(value);
});
var ctx = document.getElementById('chart');
var myBarChart = new Chart(ctx, {
type: 'pie',
data: {
labels: myLabels,
datasets: [{
label: 'Labels',
data: myData,
backgroundColor: [
'rgba(75, 192, 192, 0.2)',
'rgba(255, 99, 132, 0.2)'
],
borderColor: [
'rgba(75, 192, 192, 1)',
'rgba(255,99,132,1)'
],
borderWidth: 1
}]
},
options: {
responsive: true,
maintainAspectRatio: false
}
});
}
});
});
</script>
This is what I came up with having very minimum knowledge of charts.这就是我想出的对图表的了解非常少的方法。 For time being I plan on plotting the data on a pie chart.暂时我打算在饼图上绘制数据。
Console Log Result控制台日志结果
{insert: 0, query: 524, update: 0, delete: 0, getmore: 22492, …}
command: 169411
delete: 0
getmore: 22492
insert: 0
query: 524
update: 0
__proto__: Object
You are creating a new Chart()
every time through your $.each()
loop.您每次都通过$.each()
循环创建一个new Chart()
。
Your logic goes like this:你的逻辑是这样的:
for each (key, value) in res:
create a new Chart containing just this (key, value)
You almost certainly want this:你几乎肯定想要这个:
create empty arrays myLabels[] and myData[]
for each (key, value) in res:
add key to myLabels[]
add value to myData[]
then
create one (and only one) new Chart using myLabels[] and myData[]
Your data
property for new Chart()
will then look like this: new Chart()
的data
属性将如下所示:
data: {
labels: myLabels,
datasets: [{
label: 'Labels',
data: myData,
backgroundColor: [
'rgba(75, 192, 192, 0.2)',
'rgba(255, 99, 132, 0.2)'
],
borderColor: [
'rgba(75, 192, 192, 1)',
'rgba(255,99,132,1)'
],
borderWidth: 1
}]
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.