我已经设法使用Chart.js在我的Rails应用程序中创建了一个图表,但由于某种原因,当第一次加载视图时,图表不会显示。如果我刷新页面,它会正确显示,我无法解决原因。有什么建议吗?
statement.html.erb:
....
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12" style="height:350px">
<canvas id="canvas"></canvas>
</div>
<script type="text/javascript">
var data = [
{
value: gon.creditTotal,
color:"#F7464A",
highlight: "#FF5A5E",
label: "Red"
},
{
value: gon.assetTotal ,
color: "#46BFBD",
highlight: "#5AD3D1",
label: "Green"
}
];
var ctx = document.getElementById("canvas").getContext("2d");
var myChart = new Chart(ctx).Pie(data);
</script>
注意:我已尝试将javascript包装在以下内容中,但我仍然遇到同样的问题:
window.onload = function(){
***here***
}
的application.js:
//= require jquery
//= require bootstrap
//= require jquery_ujs
//= require jquery.ui.all
//= require Chart
//= require turbolinks
//= require jquery.turbolinks
//= require_tree .
的Gemfile:
gem 'rails', '4.2.2'
gem 'bootstrap-sass', '3.2.0.0'
gem 'sass-rails', '5.0.2'
gem 'uglifier', '2.5.3'
gem 'coffee-rails', '4.1.0'
gem 'jquery-rails', '4.0.3'
gem 'jquery-ui-rails', '~> 4.2.1'
gem 'turbolinks', '2.3.0'
gem 'jquery-turbolinks'
gem 'jbuilder', '2.2.3'
gem 'sdoc', '0.4.0', group: :doc
gem 'chart-js-rails'
gem 'gon'
答案 0 :(得分:0)
这就是我使用turbolinks工作我的chart.js的方法
var ready = function() {
$.ajax({
url: "myurl.json",
type: "get",
async: true,
datatype : 'string'
}).done (function (data) {
var years = [];
var obstaravania = [];
var trzby = [];
var zisk = [];
var obstarcolor=[];
var trzbycolor=[];
var ziskcolor=[];
for(var i in data) {
years.push(data[i].year);
obstaravania.push(data[i].obstaravanie);
trzby.push(data[i].trzby);
zisk.push(data[i].zisk);
obstarcolor.push('#c0392b');
trzbycolor.push('#337ab7');
ziskcolor.push('#27ae60');
}
var chartdata = {
labels: years,
datasets : [
{
label: 'Obstarávania',
backgroundColor: obstarcolor,
labelColor: [ '#c0392b'],
data: obstaravania
},
{
label: 'Tržby',
backgroundColor:trzbycolor,
labelColor: [ '#337ab7'],
data: trzby
},
{
label: 'Zisk',
backgroundColor:ziskcolor,
labelColor: [ '#27ae60'],
data: zisk
}
]
};
var barOptions = {
responsive: true
};
var ctx2 = $("#mychart");
var newchart = new Chart(ctx2, {type: 'bar', data: chartdata, options:barOptions});
});
//});
};
$(".contractors.showcontractor").ready(ready);
document.addEventListener('turbolinks:before-cache', function() {
if ($('#mychart').width >1) {newchart.destroy() ;}
});
$(".contractors.showcontractor").on('turbolinks:ready', ready);