节点js mysql查询结果呈现到pug页面中的chart.js标签

368yc8dk  于 2022-11-07  发布在  Chart.js
关注(0)|答案(3)|浏览(159)

当我发出get请求的时候,我有一个奇怪的行为。一个对mysql的查询调用了sells(float)group by days(nvarchar)的总数。我做了两个数组(total和datas),在那里我推送了结果的内容

router.get('/movmensili', function(req, res ,next){
 if(!req.session.user){
 return res.redirect('/'); 
} 
executeQuery("SELECT SUM(price) as Totale, Data FROM db10101.10101 group by Data order 
by Data", function(error, resmov){

    var dateArray = [];
    var totaliArray = [] ;
    for (var i = 0; i<resmov.length; i++) {
        dateArray.push(resmov[i].Data)   
    }
    for (var i = 0; i<resmov.length; i++) {
        totaliArray.push(resmov[i].Totale)   
    }

    res.render('movmensili', {title: 'movs', date: (dateArray), totali: totaliArray
    });
   });   
});

console.log(dateArray); //['2022-05-01','2022-05-02','2022-05-03','2022-05-04','2022-05-05']
console.log(totaliArray); //[ '4.00', '5.50', '3.00', '1.75', null ]

到目前为止一切都很好,一旦我打开我的Pug页面,我就可以用Chart.js绘制一个条形图,这两个数组用于图表轴,包含数字值,销售总额没有问题,但xlabel应该是字符串。到目前为止,xlabel是2016(=2022减去05减去01),2015,2014等等....

canvas#myChart(style='width: 100%; height: 100%; margin: 10 auto')
 script.
    const xlabels = [#{date}]  //[2022-05-01,2022-05-02,2022-05-03,2022-05-04,2022-05-05]

    const ydatas = [#{totali}] //[4.00,5.50,3.00,1.75,]

我无法转换/转换/字符串化x值以获得所需的结果。有什么建议吗?

6l7fqoea

6l7fqoea1#

大卫,这对我很有效。您确定在渲染时正确传递了标签吗(尝试日期:用dateArray代替日期:(dateArray))。我没有为这个页面创建一个呈现函数,所以硬编码标签和数据数组:

script.
            var labels = ['2022-05-01','2022-05-02','2022-05-03','2022-05-04','2022-05-05',]
            var data = {
                labels: labels,
                datasets: [{
                label: 'My First dataset',
                backgroundColor: 'rgb(255, 99, 132)',
                borderColor: 'rgb(255, 99, 132)',
                data: ['4.00', '5.50', '3.00', '1.75', null],
                }]
            };
            var config = {type: 'line',data: data,options: {}};
            var myChart = new Chart(document.getElementById("myChart"),config);
uurv41yg

uurv41yg2#

不是最好的解决方案,但它可以工作....异步函数GetData()

var xlabel = '#{date}';
        var xlabel = xlabel.replace(/&quot;/g, '"'); 
        alert(xlabel);
        var xlabel = xlabel.split(",");
        alert(xlabel);

        for(i = 0; i < xlabel.length; i += 1){
         xlabel[i] = xlabel[i];
         //alert(numarray[i]);
         xlabels.push(xlabel[i]);
        }
k2arahey

k2arahey3#

如果我将标签硬编码为:

const xlabels = [#{date}]

而不是从页面渲染导入,一切都很好。这正是问题的关键。dateArrayconsole.log和我希望的xlabels完全一样,而一旦导入引号就消失了

console.log(dateArray); // ['2022-05-01','2022-05-02','2022-05-03','2022-05-04','2022-05-05']
const xlabels = [#{date}]; // [2022-05-01,2022-05-02,2022-05-03,2022-05-04,2022-05-05]

相关问题