如何使用express+ejs+chartjs将服务器端的对象以图表的形式显示到客户端?

问题描述 投票:0回答:1

我试图将两个对象权重(具有整数值的列表)和进度数据(具有字符串值的列表)从服务器端传递到客户端。在客户端,我陷入了如何将列表数据渲染为图表值的困境,如下所述

服务器端: ''' res.render("viewProgress.ejs",{weights:weights,progressDatas:progressDatas}); '''

客户端:

<body>
   <canvas id="progressChart"></canvas>
   <script>
     const ctx = document.getElementById('progressChart').getContext('2d');
     const tempChart = new Chart(ctx, {
       type: 'bar',
       data: {
         labels: { pdatas }, // How to correctly render pdatas?
         datasets: [{
           label: 'weight',
           data: { weightData }, // How to correctly render weightData?
           backgroundColor: ['#A5DD9B'],
           borderColor: ['#416D19'],
           borderWidth: 1,
         }]
       },
       options: {
         scales: {
           y: {
             beginAtZero: true
           }
         }
       }
     });
   </script>
</body>

我被困在这部分 感谢您的任何建议

node.js express chart.js ejs destructuring
1个回答
0
投票

我找到答案了

Server side:

res.render("viewProgress.ejs",{weights:weights,progressDatas:progressDatas}); 


Client side:

<body>
     <canvas id="progressChart"></canvas>
<script>
     const ctx = document.getElementById('progressChart').getContext('2d');
     const tempChart = new Chart(ctx, {
     type: 'bar',
     data: {
     labels: <%- JSON.stringify(locals.progressDatas)%>, // Now the progressDatas is rendered successfully
     datasets: [{
       label: 'weight',
       data:<%- JSON.stringify(locals.weights)%>, // Now the weights is rendered successfully
       backgroundColor: ['#A5DD9B'],
       borderColor: ['#416D19'],
       borderWidth: 1,
     }]
   },
   options: {
     scales: {
       y: {
         beginAtZero: true
        }
       }
     }
   });
 </script>
 </body>
© www.soinside.com 2019 - 2024. All rights reserved.