【问题标题】:Populating Highcharts chart with data received from MySQL使用从 MySQL 接收的数据填充 Highcharts 图表
【发布时间】:2016-03-09 19:57:27
【问题描述】:

我是网络编程的新手,这里的东西是为我的学士学位项目准备的。我正在做一个电能表,我想查看我选择的两个日期之间的测量数据,这些数据存储在数据库中。我设法通过 AJAX 将数据从表单传递到读取数据库的 PHP 文件,并且我成功地将 JSON 编码的数据接收到我的控制台日志中。

问题是图表没有填充任何数据,它只显示了一个尴尬的时间范围。

JavaScript - 包含在 index.php 中,而不是 *.js 文件中

$(document).ready(function() {

$('form.energy_consumption_datepicker').on('submit', function() {

    var that = $(this),
    url = that.attr('action'),
    type = that.attr('method'),
    data = {};

    that.find('[name]').each(function(index, value) {

    var that = $(this),
    name = that.attr('name'),
    value = that.val();

    data[name] = value;
    });

    $.ajax ({

        url: url,
        type: type,
        data: data,
        dataType: "json",
        success: function (response) {
            console.log(response);

            $(function() {
        $('#custom_energy_consumption_chart').highcharts({
            chart: {
                zoomType: 'x'
            },
            title: {
                text: 'Instantaneous absorbed power'
            },
            xAxis: {
                type: 'datetime'
            },
            yAxis: {
                title: {
                    text: 'kW'
                },
                labels: {
                    formatter: function() {
                        return this.value / 1000; // formatted number for kW
                    }
                }
            },

            credits: {
                enabled: false
            },
            tooltip: {
                pointFormat: '<b>{point.y} W </b>'
            },
            plotOptions: {
                area: {
                    fillColor: {
                        linearGradient: {
                            x1: 0,
                            y1: 0,
                            x2: 0,
                            y2: 1
                        },
                        stops: [
                            [0, Highcharts.getOptions().colors[0]],
                            [1, Highcharts.Color(Highcharts.getOptions().colors[3]).setOpacity(0).get('rgba')]
                        ]
                    },
                    marker: {
                        enabled: true,
                        symbol: 'circle',
                        radius: 3,
                        states: {
                            hover: {
                                enabled: true
                            }
                        }
                    }
                }
            },
            series: [{
                color: '#00d5ff',
                type: 'area',
                name: 'Watts',
                data: response
            }]
        });

        });

        $(".custom_energy_consumption").show(350);

        }

    });
    return false;
});

});

index.php - 部分

    <script src="../../js/highcharts.js"></script>
    <script src="../../js/highcharts-more.js"></script>
    .
    .
    <div class="energyConsumption" style="width: auto; height: 400px; margin: 80px auto auto 80px; display:none;">

        <h3 align="left">Choose the period to display the energy consumption</h3>

        <form class="energy_consumption_datepicker" action="custom_chart.php" method="post">

            <div class="input-control text" id="fromDatepicker">

                <input name="fromDate" id="fromDatepicker_input" type="text" data-validate-func="date" data-validate-func="required" data-validate-hint="Please select a date" data-validate-hint-position="bottom">
                <span class="input-state-error mif-warning"></span>
                <span class="input-state-success mif-checkmark"></span>
                <button class="button"><span>From</span></button>

            </div>

            <div class="input-control text" id="toDatepicker">

                <input name="toDate" id="toDatepicker_input" type="text" data-validate-func="date" data-validate-func="required" data-validate-hint="Please select a date" data-validate-hint-position="bottom">
                <span class="input-state-error mif-warning"></span>
                <span class="input-state-success mif-checkmark"></span>
                <button class="button"><span>To</span></button>

            </div>

            <input type="submit" class="button primary" value="Show">

        </form>

        <div class="custom_energy_consumption" id="custom_energy_consumption_chart" style="width: auto; height: 400px; margin: 50px auto; display:none"></div>

    </div>

custom_chart.php

<?php

    $fromDate = $_POST["fromDate"];
    $toDate = $_POST["toDate"];

    header('Content-Type: application/json');

    $servername = "localhost";
    .
    .
    $dbname = "smart_meter";

    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    } 

    $sql = "SELECT EXTRACT(year FROM date) 'year', EXTRACT(month FROM date)-1 'month', EXTRACT(day FROM date) 'day', EXTRACT(hour FROM date) 'hour', EXTRACT(minute FROM date) 'minute', energy FROM energy_data WHERE date BETWEEN '$fromDate' AND '$toDate'";
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
        // output data of each row
        while($row = $result->fetch_assoc()) {
            $customPc[] = "[Date.UTC(" . $row["year"] . "," . $row["month"] . "," . $row["day"] . "," .  $row["hour"] . "," .  $row["minute"] . ")," . $row["energy"] . "]";
        }
    } else {
        echo 0;
    }
    $conn->close();

    echo json_encode(join($customPc, ','));

    ?>

控制台日志中收到的数据:

[Date.UTC(2016,2,8,14,35),1534],[Date.UTC(2016,2,8,14,35),1534],[Date.UTC(2016,2, 8,14,35),1534],[Date.UTC(2016,2,8,14,35),1534], ... [Date.UTC(2016,2,9,18,18),1534],[Date.UTC(2016,2,9,18,18),1534],[Date.UTC(2016,2,9,18 ,19),1534],[日期.UTC(2016,2,9,18,19),1534]

我将“数据:响应”中的响应替换为接收到的数据,但写入“数据:[此处的控制台数据]”,效果很好。

有人知道这里会发生什么吗?任何建议都会有所帮助。

谢谢!

【问题讨论】:

    标签: php mysql ajax highcharts


    【解决方案1】:

    问题是 JSON 中的函数没有被评估。这意味着您的 Date.UTC() 未触发,因此不会返回时间戳。修复方法是从您的 JSON 中删除 Date.UTC() 并在那里放置时间戳。

    在 PHP 中,您可以使用 date 函数并将 UNIX 时间戳乘以 1000(转换为 javascript 时间戳)

    【讨论】:

    • 这个也不走运。我不知道如何正确传递 Highcharts 的另一种时间格式。
    • 在 PHP 中,您可以使用 strtotime() 函数将字符串转换为时间戳。将字段乘以 1000 并推送到 json。
    【解决方案2】:

    我猜这是错误的。

    if ($result->num_rows > 0) {
        // output data of each row
        while($row = $result->fetch_assoc()) {
            $customPc[] = "[Date.UTC(" . $row["year"] . "," . $row["month"] . "," . $row["day"] . "," .  $row["hour"] . "," .  $row["minute"] . ")," . $row["energy"] . "]";
        }
    } else {
        echo 0;
    }
    

    试试这个。

     if ($result->num_rows > 0) {
        // output data of each row
        $counter = 0;
        while($row = $result->fetch_assoc()) {
            $customPc[$counter] = array("year"=>date('Y',strtotime($row["year"])), "month"=>date('F',strtotime($row["month"])),"day"=>$row["day"],"hour"=>$row["hour"], "minute"=>$row["minute"],"energy"=> $row["energy"] );
            $counter ++;
        }
    } else {
        echo 0;
    }
    

    【讨论】:

    • 现在我得到这样的东西:[Object, ..., Object]
    • 我猜你没有这样做 echo json_encode(join($customPc, ','));试试 :echo json_encode($customPc);并尝试在您的 javascript 中使用 JSON.parse(response)
    • 尝试在您的控制台上查看 ajax 响应使用情况、chrome 或 firefox 的 firebug 扩展。
    • 我试过 JSON.parse(response) 没有运气。如果我用图表函数变量替换萤火虫控制台中收到的字符串,它就可以工作。我认为问题在于我如何将接收到的字符串传递给图表函数。
    • 试试 jQuery.parseJSON(response);你能告诉我响应数组来验证 json 格式是否正确吗?
    【解决方案3】:

    这里检查的内容有点多,但一个大问题是你发回数据的方式:

        while($row = $result->fetch_assoc()) {
            $customPc[] = "[Date.UTC(" . $row["year"] . "," . $row["month"] . "," . $row["day"] . "," .  $row["hour"] . "," .  $row["minute"] . ")," . $row["energy"] . "]";
        }
    
    ...
    
    echo json_encode(join($customPc, ','));
    

    使用字符串连接和join 将导致一个大字符串用引号括起来,例如"all the data concatenated here"。

    您需要一个包含所有数据点的实际嵌套数组,因此一个长字符串不会对 highcharts 产生任何有用的结果。

    您应该生成一个嵌套数组结构并将其作为 json 发送到您的 javascript。比如:

        while($row = $result->fetch_assoc()) {
            // Add an array with 2 values to your data array
            $customPc[] = array(
                "Date.UTC(" . $row["year"] . "," . $row["month"] . "," . $row["day"] . "," .  $row["hour"] . $row["minute"],
                $row["energy"]
            );
        }
    
    ...
    
    // Encode the data array as json
    echo json_encode($customPc);
    

    我不确定生成的日期是否会这样工作,也许您需要直接在 php 中生成日期本身,但这更接近您的需要。

    【讨论】:

    • 感谢您的意见。通过您的编辑,我在控制台中收到错误 link,数据如下所示: [Array[1], Array[1], ..., Array[1]]
    • @SebastianN。如果结构和数据符合您的要求,您应该首先检查 php,例如使用 var_dump($customPc)。
    • 我已经尝试用 firebug 调查控制台,我收到的字符串看起来不错,如果我在函数中替换它,它就可以工作。我认为问题在于我如何将接收到的字符串传递给图表函数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-19
    • 1970-01-01
    • 2012-05-28
    相关资源
    最近更新 更多