使用 AJAX、PHP 和 MySQL 链填充 HTML select 个框

Chain populate HTML select boxes using AJAX, PHP and MySQL

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

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

通过 select 从第一个预填充的 <select> 框中获取其中一个值 - 第二个 <select> 框从基于数据库 table 的相关数据中填充在第一个 <select> 框中 select 编辑了什么选项。

因此,按照下图,如果我 select 来自第一个 <select> 框的位置,那么第二个 <select> 框将填充位于那个位置。

我的数据库中的所有数据和关系都已就绪。我已经在数据库端测试了我的 SQL 查询并且它们有效。现在我需要将其全部放入一个 PHP 脚本中,该脚本将通过从表单调用 AJAX 来调用。

到目前为止,我所做的是尝试将 $.ajax 请求从此表单发送到名为 jQueryHelper.php 的 PHP 脚本,而该脚本又应该 return我将 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(位于<form>上方的<body>):

<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 事件毫无问题地触发,我收到一个带有 selected 选项值的警报(在我的例子中,它是位置的 ID数据库)。 $.ajax 嵌套更深的部分不想工作。 整个网站存储在 LAMP 服务器上。整个网站都在里面:/mywebsites/project/www/ 该表单位于 views 文件夹内,该文件夹与其他视图一起包含在根级别的脚本中以显示完整页面。 jQueryHelper.phpclasses 文件夹内。

我不知道,也许有更简单的方法。

在你的 switch 块中,你不应该 return 来自 getAssignedSuites 调用的结果 return 吗?

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

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

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

AJAX 调用找不到 jQueryHelper.php。 将 url/classes/jQueryHelper.php 更改为 classes/jQueryHelper.php 修复了路径问题。