使用Ajax正确方式刷新ChartJS(v2.6.0)中的Bar Char [英] Refresh the Bar Char in ChartJS (v2.6.0) Using Ajax Correct Way

查看:115
本文介绍了使用Ajax正确方式刷新ChartJS(v2.6.0)中的Bar Char的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在刷新下拉列表中的条形图.我只是想知道我是否以正确的方式进行操作.每次我用代码替换现有画布时,都用新画布替换.有没有更好的方法来实现相同的目标?

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?

我的JS代码:

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
                        }
                    ]
                }

            });

        }
    });
};

推荐答案

肯定有一些更好的方法,我一直在使用Chart.js实时更新图表,而要完成所需的一种好方法是用一些方法声明图表最初预定义的设置.

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: {}
}

这样,每当需要更新图表时,只需访问已存在的图表即可.并将数据更新为从ajax调用中获取的数据,并使用chart.update()方法,这样您就可以继续使用预先存在的画布

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();
    }
});

希望这会有所帮助!

这篇关于使用Ajax正确方式刷新ChartJS(v2.6.0)中的Bar Char的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆