首页 > 解决方案 > 如何根据 Node JS 发送的 JSON 数据在我的 HTML 页面上显示图表

问题描述

我希望在客户端 HTML/JS 上显示我的 JSON 数据,这些数据是使用chartjsD3.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

标签: javascripthtmlajaxd3.jschart.js

解决方案


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

推荐阅读