1

我正在使用 php & Charts.js 生成基于 html 的数据图表<select> 我的问题是,即使没有从 html 中选择任何内容,也会<select>在页面底部显示空白图表,而不是在我的块中显示echo语句else {}.

我应该如何重写此语法,以便在从 html 中进行选择时创建图表<select>

<body>
    <form method="POST">
    <p>Select Sales Name:
            <select name="Name">
                <option value="">Select A Name...</option>
                <option value="Joe">Joe</option>
                <option value="Jack">Jack</option>
                <option value="Jerry">Jerry</option>
                <option value="Jimmy">Jimmy</option></select></p>
        <input type="submit" name="submit" value="Show Me">
    </form>
</body>
<?php
if (isset($_POST['submit'])) {
    $whatsalesprsn = $_POST['Name'];
    if ($whatsalesprsn == "Joe") { $region = "East"; }
    if ($whatsalesprsn == "Jack") { $region = "West"; }
    if ($whatsalesprsn == "Jerry") { $region = "North"; }
    if ($whatsalesprsn == "Jimmy") { $region = "South"; }
    if (isset($region)) {
        $query = "Select * from salesdata where salesregion = '$region'";
        $db->setQuery($query);
        $rows = $db->loadColumn();
        $output = array();
        for ($i = 0; $i <= 3; $i++) {
        $column = $db->loadColumn($i);
        array_push($output, $column);
    }
    $data = json_encode($output[0]);
    } else { echo "PLease select a sales person to display data for."; }
}
?>

<html>
    <head>
        <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
    </head>
    <body>
        <div id="container" style="width: 75%;">
            <canvas id="canvas"></canvas>
        </div><script>
            //JavaScript to generate chart
        </script>
    </body>
</html>
4

2 回答 2

0

您需要添加if statement功能empty()。SO if将使用函数if statement检查$whatsalesprsn变量是否为空empty()

if(!empty($whatsalesprsn)){
 $whatsalesprsn = $_POST['Name'];
    if ($whatsalesprsn == "Joe") { $region = "East"; }
    if ($whatsalesprsn == "Jack") { $region = "West"; }
    if ($whatsalesprsn == "Jerry") { $region = "North"; }
    if ($whatsalesprsn == "Jimmy") { $region = "South"; }
    if (isset($region)) {
        $query = "Select * from salesdata where salesregion = '$region'";
        $db->setQuery($query);
        $rows = $db->loadColumn();
        $output = array();
        for ($i = 0; $i <= 3; $i++) {
        $column = $db->loadColumn($i);
        array_push($output, $column);
    }
    $data = json_encode($output[0]);
}
于 2017-07-19T13:28:49.050 回答
0

你一定在某个地方打电话new Chart(...)。如果你在没有传递有效数据的情况下这样做,那么 Chart.js 将创建一个空图表(因为这是你告诉它的)。

如果您没有有效数据(即<select>元素中没有选择任何内容),请不要实例化 Chart.js。就像是:

if (data.length) {
    new Chart(...);
}
于 2017-07-19T13:25:02.563 回答