Chart.js只是随机出现,并在页面刷新时消失

时间:2014-11-07 17:01:02

标签: javascript jquery chart.js

尝试使用chart.js,但我遇到了图表加载的问题....有时候。其他时候它没有,它在页面刷新时消失。有任何想法吗?这是在Chrome和Safari中测试的。

<canvas id="myChart" width="400px" height="400px"></canvas>

<script>
    $.getJSON('includes/salesjson.php', function(data){
    var lineChartData = {
        labels : data[0],
        datasets : [
            {
                label: "My First dataset",
                fillColor : "rgba(220,220,220,0.2)",
                strokeColor : "rgba(220,220,220,1)",
                pointColor : "rgba(220,220,220,1)",
                pointStrokeColor : "#fff",
                pointHighlightFill : "#fff",
                pointHighlightStroke : "rgba(220,220,220,1)",
                data : data[1]
            }
        ]

    }

window.onload = function(){
    var ctx = document.getElementById("myChart").getContext("2d");
    window.myLine = new Chart(ctx).Line(lineChartData, {
        responsive: false
    });
}
     });

</script>

1 个答案:

答案 0 :(得分:2)

您在json返回内部的特定window.onload中放错了代码,具体取决于函数(数据)何时返回此显示图表,位于改进和固定代码(未测试)下方。

$(function(){
        $.getJSON('includes/salesjson.php', function(data){
            var lineChartData = {
                labels : data[0],
                datasets : [
                    {
                        label: "My First dataset",
                        fillColor : "rgba(220,220,220,0.2)",
                        strokeColor : "rgba(220,220,220,1)",
                        pointColor : "rgba(220,220,220,1)",
                        pointStrokeColor : "#fff",
                        pointHighlightFill : "#fff",
                        pointHighlightStroke : "rgba(220,220,220,1)",
                        data : data[1]
                    }
                ]
            };

            var ctx = document.getElementById("myChart").getContext("2d");
            var chart = new Chart(ctx).Line(lineChartData, {
                responsive: false
            });
        });

    });