我希望在客户端HTML / JS上显示我的JSON数据,该数据是使用chartjs或D3.js
(或任何相关的东西)以图表的形式从服务器端NodeJS API获取的。
这是我的 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>
这就是我对图表知识非常了解的结果。我暂时计划在饼图中绘制数据。
控制台日志结果
{insert: 0, query: 524, update: 0, delete: 0, getmore: 22492, …}
command: 169411
delete: 0
getmore: 22492
insert: 0
query: 524
update: 0
__proto__: Object
您new Chart()
每次都在$.each()
循环中创建一个。
您的逻辑如下:
for each (key, value) in res:
create a new Chart containing just this (key, value)
您几乎可以肯定要这样做:
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[]
您的data
资产new Chart()
将如下所示:
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
}]
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句