使用 Ajax 正确方式刷新 ChartJS (v2.6.0) 中的 Bar Char [英] Refresh the Bar Char in ChartJS (v2.6.0) Using Ajax Correct Way
问题描述
我正在刷新我的条形图以更改下拉列表.我只是想知道我是否以正确的方式做这件事.每次我用新画布替换现有画布时,都在我的代码中.有没有更好的方法来实现同样的目标?
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屋!