javascript - 使用 MySQL 和 PHP 的 ChartJs

标签 javascript php jquery json mysqli

我正在尝试与 ChartJs 进行在线聊天。

我想使用php将MySQL数据推送到chartJs。

MySQL 表

id  | page_views | visitors | month |
------------------------------------| 
1   |   200      |   20     | Jan   |
2   |   100      |   10     | Feb   |
3   |   500      |   30     | March |
------------------------------------|

图表

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()]
                }
            ]

        }

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

我想为此应用 MySQL 循环。

谁能给我一个简单的例子来说明如何做到这一点?

最佳答案

ChartJS 获取 JSON 格式的数据。

您可以使用 AJAX 获取 JSON 数据。

var jsonData = $.ajax({
    url: 'http://yourdomain.com/yourfile.php',
    dataType: 'json',
}).done(function (results){

在调用 PHP 文件中,您可以对逻辑和数据库访问进行编程。然后,您可以使用 json_encode 回显数据,以 JSON 格式输出数组。

header('Content-Type: application/json');
echo json_encode($dataArray);

然后您可以将数据添加到图表中,如下所示:

var myChart = new Chart(ctx).Line(jsonData);

关于javascript - 使用 MySQL 和 PHP 的 ChartJs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36573150/

相关文章:

javascript - jQuery float 条形数字 : Numbers positioning

jQuery ^= 与 |=。不必要?

javascript - 破坏 JavaScript 代码的 IE8 更改的完整列表

javascript - 他们的任何带有幻灯片的响应式灯箱是否具有适当的滑动?

javascript - JavaScript、Node.js 中回调的困惑

Javascript 倒计时显示链接

php - AJAX/jQuery 和 Chrome 的奇怪行为

php - 为什么 PHP 的 oci_connect 不返回 false?

javascript - 如何从数组中找到更长的字符串?

php - 基于单选按钮状态的链接点击动态 href 生成 : PHP interaction with javascript