chart.js php实时更新

时间:2017-04-12 07:12:12

标签: php ajax chart.js

使用Chart.JS(http://www.chartjs.org/docs/),我想在页面中显示数据库的实时更新结果。 有人能告诉我一个AJAX的例子如何获得结果并在这段代码中传递它们吗?

PHP:

$query2 = "SELECT * FROM CMS_Stats ";
$result2 = $conn->query($query2);

while($row2 = $result2->fetch_assoc()) {
   $members[] = $row2['MembersOnline'];
   $guests[] = $row2['GuestsOnline'];
}

JS:

var canvas = document.getElementById('myChart');
var data = {
    labels: ['Now'],
    datasets: [
        {
            label: "Members online",
            lineTension: 0.3,
            backgroundColor: "rgba(75,192,192,.90)",
            borderColor: "rgba(75,192,192,1)",
            pointRadius: 3,
            pointHitRadius: 10,
            data: <?php echo json_encode($members) ?>,
        },
        {
            label: "Guests online",
            lineTension: 0.3,
            data: <?php echo json_encode($guests) ?>,
            backgroundColor: "rgba(255, 185, 84,.90)",
            pointBorderColor: "rgba(211,84,0 ,1)",
            pointBackgroundColor: "#fff",
            pointRadius: 3,
            pointHoverBackgroundColor: "rgba(211,84,0 ,1)",
            pointHoverBorderColor: "rgba(220,220,220,1)"
        }
    ]
};

var option = {
    showLines: true
};
var myLineChart = Chart.Line(canvas,{
    data:data,
  options:option
});

1 个答案:

答案 0 :(得分:0)

您需要使用间隔运行AJAX:

setInterval(ajaxFunction(), 5000); // 5 sec

在该功能中你必须调用AJAX

function showHint(str) {

if (str.length == 0) { // case that doesn't call AJAX (can be discluded)
    document.getElementById("txtHint").innerHTML = "";
    return;
} else {  // case that calls AJAX
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) { //successfully getting answer
            document.getElementById("txtHint").innerHTML = this.responseText; // this.responseText is answer you get
        }
    };
    xmlhttp.open("GET", "gethint.php?q=" + str, true); // your php file that works with recieved data and echoes answer
    xmlhttp.send();
}

}

AJAX部分只是来自w3schools的随机片段,如果您是AJAX的新手,那么只需搜索AJAX PHP