图表在数据集更新后消失

时间:2019-12-23 15:48:23

标签: javascript jquery chart.js

我正在使用常规的HTML + js设置,并且拥有JQuery + ChartJS 2.9.3 我正在创建折线图,就像示例一样。 我正在使用JQuery的getJSON从服务器查询JSON。我正在相应地对其进行处理,并且最终数据集和标签的格式正确(已通过调试检查)。 单击获取并解析JSON的更新按钮时,图表消失了,只是重新显示在重新绘制(例如:移动窗口)上,以正确的方式处理了我所有的数据。

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<body>
    <canvas id="canvas"></canvas>
    <br />
    <br />
    <input type="number" id="limit" min="3" max="100" value="10" step="1" />
    <button type="button" id="update">Update</button>
    <script>
        const colors = ["#fcba03", "#56fc03", "#56fc03", "#054eeb", "#8f05eb", "#eb05e0", "#05ebeb"]

        Object.map = function (o, f, ctx) {
            ctx = ctx || this;
            var result = {};
            Object.keys(o).forEach(function (k) {
                result[k] = f.call(ctx, o[k], k, o);
            });
            return result;
        }

        var config = {
            type: 'line',
            data: {
                labels: [],
                datasets: []
            },
            options: {
                responsive: true,
                title: {
                    display: true,
                    text: "Qualité de l'air"
                },
                tooltips: {
                    mode: 'index',
                    intersect: false,
                },
                hover: {
                    mode: 'nearest',
                    intersect: true
                },
                scales: {
                    x: {
                        display: true,
                        scaleLabel: {
                            display: true,
                            labelString: 'Time'
                        }
                    },
                    y: {
                        display: true,
                        scaleLabel: {
                            display: true,
                            labelString: 'Value'
                        }
                    }
                }
            }
        };

        window.onload = function() {
            var ctx = document.getElementById('canvas').getContext('2d');
            window.myChart = new Chart(ctx, config);
        };

        document.getElementById('update').addEventListener('click', updateGraph);

        function updateGraph() {
            var limit = document.getElementById('limit').value;
            $.getJSON("http://localhost/api.php?limit=" + limit, function (obj) {
                var labels_obj = Object.map(obj, (value) => { return value.numeric.time; });
                var arr = $.map(obj, function (el) { return el });

                for (const key in obj) {
                    if (obj.hasOwnProperty(key)) {
                        const element = obj[key];

                        delete element.numeric.time;
                    }
                }

                var dataset_names = Object.keys(obj[0].numeric);

                var datasets_obj = Object.map(dataset_names, (element, index) => {
                    var data = Object.values(Object.map(obj, (value) => { return value.numeric[dataset_names[index]]; }));

                    return {
                        backgroundColor: colors[index],
                        borderColor: colors[index],
                        fill: false,
                        label: element,
                        data: data,
                    };
                });

                window.myChart.config.data.labels = Object.values(labels_obj);
                window.myChart.config.data.datasets = Object.values(datasets_obj);
            });

            window.myChart.update();
        }
    </script>
</body>

我的JSON看起来像这样:

{
  "0": {
    "numeric": {
      "NH3": "0.995879",
      "CO": "0.333835",
      "NO2": "0.68154",
      "C3H8": "0.406195",
      "C4H10": "0.986352",
      "CH4": "0.713178",
      "H2": "0.606834",
      "time": "2019-11-27 09:52:56"
    },
    "analog": {
      "HCHO": "0.688368",
      "MQ2": "0.230614",
      "time": "2019-11-27 09:51:00"
    }
  },
  "1": {
    "numeric": {
      "NH3": "0.406223",
      "CO": "0.440095",
      "NO2": "0.981807",
      "C3H8": "0.588751",
      "C4H10": "0.998331",
      "CH4": "0.225404",
      "H2": "0.132026",
      "time": "2019-11-27 09:52:55"
    },
    "analog": {
      "HCHO": "0.482279",
      "MQ2": "0.768992",
      "time": "2019-11-27 09:50:59"
    }
  } (etc...)
}

已尽一切努力使该图表不会消失。更新时,我还会收到此js错误:TypeError: this.getDatasetMeta(...).controller is null chart.js@2.9.3:7:107693

非常感谢!

1 个答案:

答案 0 :(得分:0)

发现了问题: 由于getJSON是异步执行的,之后又调用了chart.update(),因此图表被更新,然后数据被更改,从而导致该错误。 确保chart.update()调用在$.getJSON(){...}内部。