jQuery canvasjs甜甜圈图实时检索数据

时间:2018-11-09 09:30:28

标签: javascript jquery charts canvasjs

我正在使用Donut Chart

然后通过PHP从数据库中检索数据。

PHP

$q = oci_parse($c1, "SELECT DESCRIPTION, SUM(QUANTITY) AS TOTALS FROM TEST1 
GROUP BY DESCRIPTION");
oci_execute($q);
while($d = oci_fetch_array($q))
{
    $description[] = $d['DESCRIPTION'];
    $quantity[] = $d['TOTALS'];

    $nameAndCode = array();
    $nameAndCode['label'] = $d['DESCRIPTION'];
    $nameAndCode['y'] = $d['TOTALS'];           
    $namesArray[] = $nameAndCode;
}

$dataPoints = array(
    "dataPoints"     => $namesArray
);

echo json_encode($dataPoints);

还有JS

var dataPoints = [];

function updateChart()
{
    $.getJSON("data.php", function(result)
    {
        for (var i = 0; i <= result.dataPoints.length - 1; i++)
        {
            dataPoints.push({
                label: result.dataPoints[i].label,
                y: parseInt(result.dataPoints[i].y)
            });
        }

        chart.render();
    });
}

var chart = new CanvasJS.Chart("chartContainer", {
    data: [{
    type: "doughnut",
    innerRadius: "40%",
    showInLegend: true,
    legendText: "{label}",
    indexLabel: "{label}: #percent%",
    dataPoints: dataPoints
    }]
});

var updateInterval = 1000;

setInterval(function(){
    updateChart()
}, updateInterval);

当我尝试运行代码时,“甜甜圈图”将始终显示很多重复项。数据仅检索4个项目。

enter image description here

enter image description here

我的目的是甜甜圈图将始终实时获取数据。

我的问题,如何防止出现如此多的重复图表?

enter image description here

2 个答案:

答案 0 :(得分:0)

获取结果后,您应该首先清空dataPoints数组,然后遍历该数组以填充。

尝试类似的东西

$.getJSON("data.php", function(result)
    {
        $("#chartContainer").options.data[0].dataPoints = result;
        $("#chartContainer").CanvasJSChart().render();
    });

示例; https://jsfiddle.net/yumn325w/

答案 1 :(得分:0)

每次删除并重新创建图表容器(CANVAS)

    function updateChart()
    {
       document.getElementById("divDonutChart").innerHTML = '&nbsp;';
       document.getElementById("divDonutChart").innerHTML = '<canvas 
       id="chartContainer"> </canvas>  ';

        $.getJSON("data.php", function(result)
        {