php - 使用 AJAX、PHP 和 MySQL 链式填充 HTML 选择框

标签 php jquery mysql ajax drop-down-menu

我的特殊表单有两个选择框。在页面加载阶段,我使用 PHP 从 MySQL 数据库中填充了第一个选项。

我接下来要实现的目标如下:

通过从第一个预填充的 <select> 中选择一个值盒子-第二个<select>根据第一个 <select> 中选择的选项,用数据库表中的相关数据填充框。框。

因此,按照下图,如果我从第一个 <select> 中选择一个位置框,然后是第二个 <select>框中将填充该位置的所有套件。

enter image description here

我的数据库已准备好所有数据并建立了关系。我已经在数据库端测试了我的 SQL 查询,它们可以工作。现在我需要将其全部放入 PHP 脚本中,该脚本将通过表单中的 AJAX 调用进行调用。

到目前为止我所做的是尝试发送 $.ajax从此表单向名为 jQueryHelper.php 的 PHP 脚本发出请求该脚本又应该返回我将 alert() 的套件首先。

jQueryHelper.php:

<?php
define("DB_HOST", "127.0.0.1");
define("DB_NAME", "mydb");
define("DB_USER", "root");
define("DB_PASS", "**********");

class jQueryHelper
{
    private static $initialized = false;
    private $db_connection = null;

    private static function initialize()
    {
        if (self::$initialized)
            return;
        $this->db_connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
        self::$initialized = true;
    }

    public static function giveData()
    {
        self::initialize();
        if (!$this->db_connection->set_charset("utf8")) {
            $this->errors[] = $this->db_connection->error;
        }
        if (!$this->db_connection->connect_errno) {
                if(isset($_POST['action']) && !empty($_POST['action'])){
                    $action = $_POST['action'];
                    $theSelectedLocationId = $_POST['id'];
                    switch($action){
                        case 'getAssignedSuites': 
                            $this->getAssignedSuites($theSelectedLocationId);
                            break;
                    }
                }
        }
    }

    public static function getAssignedSuites($theSelectedLocationId){
        $sql =<<<EOF
            SELECT * FROM suites
            WHERE location_id = $theSelectedLocationId
EOF;

        $query_get_assigned_suites = $this->db_connection->query($sql);
        $rows = array();
        while($r = mysqli_fetch_assoc($query_get_assigned_suites)){
            $rows[] = $r;
        }
        echo json_encode($rows);
    }
}

// Call it!
jQueryHelper::giveData();
?>

HTML 表单:

<form method="post" action="user_todays_locations.php" name="updatetodayslocation" role="form">
    <div class="form-group">
        <label for="suite_location" class="sr-only">Assigned Locations</label>
        <select size="1" name="suite_location" class="form-control input-lg" required>
            <option value="" selected="selected" disabled>Assigned Locations</option>
            <?php $location->getAssignedLocations($login->getCurrentUserID()); ?>
        </select>
    </div>
    <!-- more divs and form controls here -->
</form>

jQuery 的 $.ajax (位于 <body> 上方的 <form> ):

<script>
// grab ID of selected location
$(function() {
    $("select[name=suite_location]").change(function() {
        var theSelectedLocationId = this.value;
        //alert(theSelectedLocationId);
        $.ajax({ url: '/classes/jQueryHelper.php',
            data: {action: 'getAssignedSuites', id: theSelectedLocationId},
            type: 'post',
            success: function(output) {
                alert(output);
            },
            error: function(jqXHR, textStatus, errorThrown) {
                if (jqXHR.status === 0) {
                    alert('Not connect.\n Verify Network.');
                } else if (jqXHR.status == 404) {
                    alert('Requested page not found. [404]');
                } else if (jqXHR.status == 500) {
                    alert('Internal Server Error [500].');
                } else if (exception === 'parsererror') {
                    alert('Requested JSON parse failed.');
                } else if (exception === 'timeout') {
                    alert('Time out error.');
                } else if (exception === 'abort') {
                    alert('Ajax request aborted.');
                } else {
                    alert('Uncaught Error.\n' + jqXHR.responseText);
                }
            }
        });
});
</script>

jQuery 的 <select> .change 事件毫无问题地触发,并且我收到一条包含所选选项值的警报(在我的例子中,它是数据库中位置的 ID)。 $.ajax嵌套更深的部分不想工作。 整个网站存储在 LAMP 服务器上。整个网站都在里面:/mywebsites/project/www/ 表格在views里面文件夹,它与其他 View 一起包含在根级别的脚本中以显示完整的页面。 jQueryHelper.php在里面classes文件夹。

我不知道,也许有更简单的方法来做到这一点。

最佳答案

在你的 switch block 中,你不应该返回从 getAssignedSuites 返回的结果吗?打电话?

switch($action){
  case 'getAssignedSuites': 
    return $this->getAssignedSuites($theSelectedLocationId);
    break;
}

然后按照@sean的建议。 echo jQueryHelper::giveData();

还有。我认为调用 $_POST 不是一个好习惯在类函数内。我建议将它们作为参数传递,例如 jQueryHelper::giveData($_POST['action'], $_POST['id'])然后使用它。

关于php - 使用 AJAX、PHP 和 MySQL 链式填充 HTML 选择框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30810742/

相关文章:

php - 使用PHP脚本、MySQL数据库发送群发邮件

javascript - 如何使用控制台选择N个复选框?

mysql - sql 如何在同一列中应用不同条件的 sum()

mysql - UNION SELECT 的问题

php - 用每行的增量数字替换特定行的字符

php - 在我的 mysql 查询中无法正常工作的地方

php - 在数组中拆分 mysql 查询,每个查询由 ";"分隔

如果悬停表单或单击输入框,jQuery 应用动画

javascript - 使用 Ajax XMLHttpRequest 上传文件

mysql - 查找一个表中与另一表中其他元素最接近的两个元素