簡體   English   中英

如何根據 Node JS 發送的 JSON 數據在我的 HTML 頁面上顯示圖表

[英]How do I display chart on my HTML page based on JSON data sent by Node JS

我希望在客戶端 HTML/JS 上顯示我的 JSON 數據,這些數據是從服務器端 NodeJS API 以圖表的形式使用chartjsD3.js的(或任何似乎相關的內容)。

這是我的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

您每次都通過$.each()循環創建一個new Chart()

你的邏輯是這樣的:

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

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM