Refresh the Bar Char in ChartJS (v2.6.0) Using Ajax Correct Way

房东的猫 提交于 2021-02-07 06:48:42

问题


I am refreshing my Bar Chart on change of a drop down. I just Want to know that am I doing it in correct way. In my code every time I am replacing my existing canvas with new one. Is there any better way to achieve same thing?

My JS Code:

var chart_= function () {

    $('#canvas_id').replaceWith('<canvas id="canvas_id" style="height:280px"></canvas>');
    $.ajax({
        type: 'POST', //post method
        url: 'url', //ajaxformexample url
        dataType: "json",
        success: function (result, textStatus, jqXHR)
        {
            // GENERATE CHART DATA
            var labels = result.obj.map(function (e) {
                return e.label;
            });
            var data = result.obj.map(function (e) {
                return e.data;
            });
            new Chart($("#canvas_id"), {
                type: 'bar',
                options: options_object,
                data: {
                    labels: labels,
                    datasets: [
                        {
                            label: "",
                            backgroundColor: '#00c0ef',
                            data: data
                        }
                    ]
                }

            });

        }
    });
};

回答1:


Definitely some better ways, I have been using Chart.js for some live updating charts and a good way to accomplish what you want is to declare an chart with some of the settings predefined initially.

var chart = new Chart( canvas, {
          type: "bar",
          data: {}
          options: {}
}

This way, whenever you need to update the chart, you just access the already existing chart. And update the data to what you get from your ajax call, and use the chart.update() method, so you can keep using the pre-existing canvas

$.ajax({
    type: 'POST', //post method
    url: 'url', //ajaxformexample url
    dataType: "json",
    success: function (result, textStatus, jqXHR)
    {
        chart.data = result;
        chart.update();
    }
});

Hope this helps!



来源:https://stackoverflow.com/questions/45386406/refresh-the-bar-char-in-chartjs-v2-6-0-using-ajax-correct-way

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!