我是js和jquery的完整新手,但是通过使用Flask和Ajax请求获取图表来正确显示我的方式。我遇到问题的地方是让图表数据刷新。如果我将其创建为新图表,我可以让图表显示正常,如下面的代码所示
$(document).ready(function() {
var getdata = $.post('/charts');
var ctx = document.getElementById('myChart').getContext('2d');
var myChart
getdata.done(function(results){
var chartData = {
labels: results['month'],
datasets: [{
label: 'Debits',
data: results['debit'],
backgroundColor: "rgba(153,255,51,0.4)"
}, {
label: 'Credits',
data: results['credit'],
backgroundColor: "rgba(255,153,0,0.4)"
}, {
label: 'Balance',
data: results['balance'],
backgroundColor: "rgba(50,110,0,0.4)"
}]
}
myChart = new Chart(ctx, {type: 'line', data: chartData});
});
$("form :input").change(function() {
year = $(this).val();
console.log(year)
$.ajax({
type: "POST",
url: "/data",
data: {'year':year},
success: function(results){
var updatedData = {
labels : results['month'],
datasets : [{
label: 'Debits',
data: results['debit'],
backgroundColor: "rgba(153,255,51,0.4)"
}, {
label: 'Credits',
data: results['credit'],
backgroundColor: "rgba(255,153,0,0.4)"
}, {
label: 'Balance',
data: results['balance'],
backgroundColor: "rgba(50,110,0,0.4)"
}]
}
myChart= new Chart(ctx, {type: 'line', data: updatedData});
}
});
});
});
但如果我将最后一行改为
myChart.update(updatedData)
没有任何反应,我没有得到任何错误,图表没有更新。没有。奇怪的是,我知道myChart是全局的,因为在Ajax请求之后我不必再创建它。
由于
答案 0 :(得分:0)
从charts.js(http://www.chartjs.org/docs/#getting-started-creating-a-chart)的文档中,首先需要更改数据,然后调用update(更新函数的参数不是数据,而是持续时间等):
.update(持续时间,懒惰)
触发图表更新。在替换整个数据对象后可以安全地调用它。这将更新所有比例,图例,然后重新渲染图表。
// duration is the time for the animation of the redraw in milliseconds
// lazy is a boolean. if true, the animation can be interrupted by other animations
myLineChart.data.datasets[0].data[2] = 50; // Would update the first dataset's value of 'March' to be 50
myLineChart.update(); // Calling update now animates the position of March from 90 to 50.
所以在你的情况下:
myChart.data = updatedData;
myChart.update();