首页 > 解决方案 > ChartJs 从数组创建图表

问题描述

我通过 ajax 获取 ChartJs 图表的数据和标签,并从中创建了一个数组。

当我制作 console.log 时,数组看起来可以正常工作,但图表没有标签也没有数据。

我在这里找到了这个问题,但它并没有解决问题。

这是我的chartJs代码:

               config = {
                    type: 'bar',
                    data: {
                        labels: labels,
                        datasets: [{
                            label: "Aufrufe",
                            data: dataarray,
                            backgroundColor: 'rgba(0, 188, 212, 0.8)'
                        }]
                    },
                    options: {
                        responsive: true,
                        legend: false
                    }
                }

以及我从 console.log 获得的数组:

在此处输入图像描述

这就是我创建数组的方式:

/* create a labels array */
                        while(year !== (new Date).getFullYear() || month !== enddate) {
                            console.log(year, month);
                            labels.push(month + " " + year);
                            month++;
                            if(month === 13) {
                                year++;
                                month = 1;
                            }

                        }

但图表只是一个空图表......

标签: javascriptchart.js

解决方案


问题是 Ajax 请求是异步的。所以图表是在没有任何数据的情况下绘制的。

必须有 ajax 请求,async: false,以便可以加载数据,然后使用数据绘制图表。


推荐阅读