You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过PHP变量在HTML中实现联动下拉框动态填充

实现下拉框联动(MVC架构)

1. 前端JavaScript逻辑修改

修改GetSelectedListenBearbeitungValue函数,通过AJAX请求后端MVC接口获取对应数据,完成第二个下拉框的重置与填充:

function GetSelectedListenBearbeitungValue(selectElement, targetSelect) {
    const selectedId = selectElement.value;
    // 清空目标下拉框
    targetSelect.innerHTML = '';

    // 发送AJAX请求到MVC控制器
    const xhr = new XMLHttpRequest();
    xhr.open('GET', '/your-controller-path/get-list-entries?listen_id=' + selectedId, true);
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.onload = function() {
        if (xhr.status === 200) {
            const entries = JSON.parse(xhr.responseText);
            // 动态生成新选项
            entries.forEach(entry => {
                const option = document.createElement('option');
                option.value = entry.entry_short;
                option.textContent = entry.entry_long;
                targetSelect.appendChild(option);
            });
        }
    };
    xhr.send();
}

2. MVC控制器实现(后端)

在控制器中添加处理请求的方法,接收listen_id参数,调用Model层获取数据并返回JSON:

// 示例:ListController.php
class ListController {
    public function getListEntries() {
        // 获取请求参数
        $listenId = $_GET['listen_id'] ?? '';
        if (empty($listenId)) {
            echo json_encode([]);
            return;
        }

        // 调用Model层查询对应数据
        $listEntryModel = new ListEntryModel();
        $entries = $listEntryModel->fetchByListenId($listenId);

        // 返回JSON格式响应
        header('Content-Type: application/json');
        echo json_encode($entries);
    }
}

3. Model层数据查询

Model层负责数据库交互,实现根据listen_id筛选条目:

// 示例:ListEntryModel.php
class ListEntryModel {
    private $dbConn;

    public function __construct() {
        // 初始化数据库连接(按你的MVC框架配置调整)
        $this->dbConn = new mysqli('localhost', 'db-user', 'db-pass', 'db-name');
    }

    public function fetchByListenId($listenId) {
        $entries = [];
        // 预处理SQL避免注入
        $stmt = $this->dbConn->prepare("SELECT entry_short, entry_long FROM listeneintraege WHERE listen_id = ?");
        $stmt->bind_param('i', $listenId);
        $stmt->execute();
        $result = $stmt->get_result();

        while ($row = $result->fetch_assoc()) {
            $entries[] = $row;
        }

        $stmt->close();
        return $entries;
    }
}

4. 前端HTML优化

你的代码中重复了两组下拉框(相同ID会导致DOM操作异常),保留一组即可,同时确保传入第二个下拉框的DOM对象正确:

<div style="position:absolute;left:356px;top:110px;width:193px;height:17px;border:1px #C0C0C0 solid;z-index:150">
    <select 
        name="cmb_listen_bearbeitung" 
        size="1" 
        id="cmb_listen_bearbeitung" 
        onchange="GetSelectedListenBearbeitungValue(this, document.getElementById('list_list_eintraege'))"             
        style="position:absolute;left:0px;top:0px;width:100%;height:100%;border-width:0px;font-family:Calibri;font-size:13px;" 
        tabindex="4">
        <?php
            if ($listen->num_rows > 0) {
                mysqli_data_seek($listen, 0);
                while ($row = mysqli_fetch_array($listen)) {
                    $listen_id = $row['listen_id'];
                    $bezeichnung = $row['bezeichnung'];
                    $selectedAttr = ($liste_ausgewaehlt == $listen_id) ? 'selected' : '';
                    echo "<option value='{$listen_id}' {$selectedAttr}>{$bezeichnung}</option>";
                }
            }
        ?>
    </select>
</div>
<div style="position:absolute;left:356px;top:163px;width:193px;height:134px;border:1px #C0C0C0 solid;z-index:151">
    <select name="list_list_eintraege" 
        size="10" 
        id="list_list_eintraege" 
        onchange="GetSelectedListenEintragValue(this)" 
        style="position:absolute;left:0px;top:0px;width:100%;height:100%;border-width:0px;font-family:Calibri;font-size:13px;" 
        tabindex="5">
        <?php
            if ($listeneintrag->num_rows > 0) {
                while ($row = mysqli_fetch_array($listeneintrag)) {
                    if ($row['listen_id'] == $liste_ausgewaehlt) {
                        echo "<option value='{$row['entry_short']}'>{$row['entry_long']}</option>";
                    }
                }
            }
        ?>
    </select>
</div>

核心流程说明

  1. 第一个下拉框选项变更时,触发AJAX请求,将选中的listen_id传递给后端控制器。
  2. 控制器调用Model层查询对应的数据,返回JSON格式的条目列表。
  3. 前端接收数据后,清空第二个下拉框并动态生成新的选项。

内容的提问来源于stack exchange,提问作者U. B.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 04:37:50