use chart.js on a page that was loaded by ajax

时间:2015-07-28 23:16:36

标签: javascript jquery ajax chart.js

I have gotten a line chart to work on a regular page. I have another page where I am using the same code, except the page is called via ajax. The chart is not appearing on the page that is called by ajax. Here is my code:

<div style="width:30%">
    <div>
        <canvas id="canvas" height="450" width="600"></canvas>
    </div>
</div>

<script>
    var randomScalingFactor = function(){ return Math.round(Math.random()*100)};
    var lineChartData = {
        labels : ["January","February","March","April","May","June","July"],
        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 : [randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor()]
            },
            {
                label: "My Second dataset",
                fillColor : "rgba(151,187,205,0.2)",
                strokeColor : "rgba(151,187,205,1)",
                pointColor : "rgba(151,187,205,1)",
                pointStrokeColor : "#fff",
                pointHighlightFill : "#fff",
                pointHighlightStroke : "rgba(151,187,205,1)",
                data : [randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor()]
            }
        ]

    }

    var ctx = document.getElementById("canvas").getContext("2d");
    var chart = new Chart(ctx).Line(lineChartData, {
        responsive: true
    });
</script>

How do I get the chart to appear on a page loaded by ajax?

1 个答案:

答案 0 :(得分:1)

您的AJAX完成后,您的DOM可能还没有准备就绪。尝试将Chart初始化包装在检查DOM是否准备就绪的内容中,如此

var interval = setInterval(function(){
    var canvas = document.getElementById("canvas");
    if (canvas) {
        var ctx = document.getElementById("canvas").getContext("2d");
        var chart = new Chart(ctx).Line(lineChartData, {
            responsive: true
        });
        clearInterval(interval)
    }
}, 100)

此外,您可能希望确保实际调用ajaxComplete函数。