ChartJS在制作新图表时删除上一张图表

时间:2017-05-31 09:56:14

标签: javascript jquery ajax charts chart.js

在下面的代码中,我使用数据库数据制作chartJS图表,这是通过提交按钮完成的,如下所示:

function showWhatSelected(str) {
$('#select2').hide();
$('#select3').hide();
    if (str == "") {
        document.getElementById("select1").innerHTML = "";
        return;
    } else { 
        if (window.XMLHttpRequest) {
            // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        } else {
            // code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                document.getElementById("select1").innerHTML = this.responseText;
            }
        };
        xmlhttp.open("GET","../controller/teamleiderController.php?action=whatToShow&value="+ str,true);
        xmlhttp.send();
    }
}

之后运行AJAX,在提交按钮中检测到更改时生成新图表:

        $.ajax({
            url: "../controller/teamleiderController.php?action=select2JSON&value="+ str +"",
            method: "GET",
            success: function(data) {
                console.log(data);
                var label = ['aanwezig', 'afwezig'];
                var aanwezigheid = [];

                for(var i in data) {
                    aanwezigheid.push(data[i].aanwezig, data[i].afwezig, );
                }

                var chartdata = {
                    labels: label,
                    datasets : [
                        {
                            backgroundColor: ['rgba(0, 65, 140, 0.8)', 'rgba(215, 165, 0, 0.8)'],
                            borderColor: 'rgba(0, 0, 0, 0)',
                            hoverBackgroundColor: ['rgba(0, 65, 140, 1)', 'rgba(215, 165, 0, 1)'],
                            hoverBorderColor: 'rgba(200, 200, 200, 0)',
                            data: aanwezigheid
                        }
                    ]
                };

                var option = {
            };

                var ctx = $("#mycanvas");

                var barGraph = new Chart(ctx, {
                    type: 'pie',
                    data: chartdata,
                    options:option
                });
            },
            error: function(data) {
                console.log(data);
            }
        });
}

我的问题是我的图表是重影,它一直显示以前的数据,有什么办法可以解决这个问题吗?我试过.destroy()和.clear(),但它们似乎都不起作用......

1 个答案:

答案 0 :(得分:1)

在制作新图表之前,您确实需要使用 .destroy() 方法删除之前的任何图表实例。

也许,您以不恰当的方式使用 .destroy() 方法,这使其无效。

这里如何在创建新图表之前正确删除/销毁任何以前的图表实例...

var meta = barGraph && barGraph.data && barGraph.data.datasets[0]._meta;
for (let i in meta) {
   if (meta[i].controller) meta[i].controller.chart.destroy();
}

在启动图表之前加上上述代码

注意: barGraph必须是全局变量。

ᴡᴏʀᴋɪɴɢᴡᴏʀᴋɪɴɢxᴀᴍᴘʟᴇᴀᴍᴘʟᴇ

var barGraph;

function init(str) {
   $.ajax({
      url: "https://istack.000webhostapp.com/json/" + str + ".json",
      method: "GET",
      success: function(data) {
         console.log(data);
         var label = ['aanwezig', 'afwezig'];
         var aanwezigheid = [];
         for (var i in data) {
            aanwezigheid.push(data[i].aanwezig, data[i].afwezig);
         }
         var chartdata = {
            labels: label,
            datasets: [{
               backgroundColor: ['rgba(0, 65, 140, 0.8)', 'rgba(215, 165, 0, 0.8)'],
               borderColor: 'rgba(0, 0, 0, 0)',
               hoverBackgroundColor: ['rgba(0, 65, 140, 1)', 'rgba(215, 165, 0, 1)'],
               hoverBorderColor: 'rgba(200, 200, 200, 0)',
               data: aanwezigheid
            }]
         };
         var option = {responsive: false};
         
         // destroy previous chart
         var meta = barGraph && barGraph.data && barGraph.data.datasets[0]._meta;
         for (let i in meta) {
            if (meta[i].controller) meta[i].controller.chart.destroy();
         }
         
         // make new chart
         var ctx = $("#mycanvas");
         barGraph = new Chart(ctx, {
            type: 'pie',
            data: chartdata,
            options: option
         });
      },
      error: function(data) {
         console.log(data);
      }
   });
}
body{overflow:hidden}button{margin-left: 45px}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<button onclick="init('t1')">Dataset 1</button>
<button onclick="init('t2')">Dataset 2</button><br>
<canvas id="mycanvas" height="180"></canvas>