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

动态生成下拉框选中值刷新后保留问题求助

解决方案

首先确保你的下拉框select标签带有正确的name属性,示例结构如下:

<form method="post">
  <select name="ResponsibleGroup">
    <!-- 动态生成的option放在这里 -->
  </select>
  <button type="submit">筛选</button>
</form>

接下来按以下步骤修改PHP代码:

  1. 获取提交的选中值
    在生成下拉框前,先获取表单提交的选中分组值:
// 从POST中获取提交的值,没有则设为空字符串
$selectedGroup = isset($_POST['ResponsibleGroup']) ? $_POST['ResponsibleGroup'] : '';
  1. 生成option时添加选中判断
    修改循环生成option的逻辑,每次循环判断当前分组是否为用户提交的选中值,是则添加selected="selected"属性:
<?php
//Section to fill the Department dropdown
// 修正SQL表名的引号错误:原语句'table` 改为 `table`
$dropdown = "SELECT `ResponsibleGroup` FROM `table` WHERE `Change_Start_Time` > '$past' AND `Change_Start_Time` < '$future' AND `Status` NOT LIKE 'Cancelled' AND `Status` NOT LIKE 'New' AND `Status` NOT LIKE 'Re-Scheduling' GROUP BY `ResponsibleGroup` ORDER BY `ResponsibleGroup` ASC";

$dropres = mysqli_query($con,$dropdown);
$selectedGroup = isset($_POST['ResponsibleGroup']) ? $_POST['ResponsibleGroup'] : '';

while($row = mysqli_fetch_array($dropres))
{
    $group = $row['ResponsibleGroup'];
    // 判断当前选项是否为提交的选中值
    $selectedAttr = ($group === $selectedGroup) ? ' selected="selected"' : '';
    // 用htmlspecialchars转义输出,避免XSS风险
    echo "<option value='" . htmlspecialchars($group) . "'" . $selectedAttr . ">" . htmlspecialchars($group) . "</option>";
}
?>
</select>
</form>

关键注意事项

  • 必须保证select标签的name属性与$_POST中的键名一致(此处为ResponsibleGroup),否则无法获取提交的值
  • 原SQL语句中表名的引号使用错误,需修正为反引号包裹表名
  • 若表单使用GET方式提交,将代码中的$_POST替换为$_GET即可
  • 加入htmlspecialchars转义输出内容,避免老旧系统出现XSS注入漏洞

内容的提问来源于stack exchange,提问作者christwigger

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 14:25:17