javascript - 如何根据 Node JS 发送的 JSON 数据在我的 HTML 页面上显示图表
问题描述
我希望在客户端 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
}]
}
推荐阅读
- php - 在 laravel excel 导入案例中找不到类 'App\imports\ExcelImport'
- c# - 如何将自动换行添加到 EditorGUILayout.TextArea?
- reactjs - 由于 gatsby webpack 配置,Jest 测试抛出错误
- jira - 使用 REST 登录 Jira
- html - 为什么 .clearfix 类的元素会崩溃?
- python - 使用 Python2 和 Python3 为 Ubuntu 18.04 安装 psycopg2
- vue.js - 在 Vuejs 中将函数作为道具传递不起作用
- node.js - 发生未处理的异常:无法读取未定义的属性“减号”
- javascript - Javascript Date.parse() 如何处理 UTC 格式的时区?
- c# - 如何遍历 user.config C# 中的用户设置