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

如何通过Ajax和JSON从MySQL填充关联公司员工的HTML下拉框

没问题,我来帮你梳理下怎么实现这个需求——核心就是通过公司ID关联查询员工数据,再动态填充到下拉框里,分前后端两步来做:

实现方案:通过公司ID填充关联员工到Select下拉框

1. 前端基础结构(HTML)

先搭好触发按钮、模态框、表单和空下拉框的基础结构,按钮上用data-id存储对应的公司ID:

<!-- 编辑公司按钮,每个按钮对应一家公司,data-id存公司ID -->
<button class="edit-company-btn" data-id="43">编辑这家公司</button>

<!-- 模态框 -->
<div id="companyModal" class="modal">
  <div class="modal-content">
    <span class="modal-close">&times;</span>
    <!-- 公司信息表单 -->
    <form id="companyForm">
      <label>公司名称:</label>
      <input type="text" id="companyName" name="companyName"><br>
      <label>公司地址:</label>
      <input type="text" id="companyAddress" name="companyAddress"><br>
      <label>关联员工:</label>
      <select id="employeeSelect" name="employeeSelect"></select>
    </form>
  </div>
</div>

2. 前端JavaScript逻辑

监听按钮点击,获取公司ID后发送异步请求,拿到数据后填充表单和下拉框:

// 获取页面元素
const modal = document.getElementById("companyModal");
const closeBtn = document.querySelector(".modal-close");
const editBtns = document.querySelectorAll(".edit-company-btn");

// 给所有编辑按钮绑定点击事件
editBtns.forEach(btn => {
  btn.addEventListener("click", function() {
    const companyId = this.getAttribute("data-id");
    // 发送AJAX请求获取公司和员工数据
    fetch(`get_company_data.php?id=${companyId}`)
      .then(response => response.json())
      .then(data => {
        // 填充公司基本信息
        document.getElementById("companyName").value = data.company.name;
        document.getElementById("companyAddress").value = data.company.address;
        
        // 清空下拉框再填充员工
        const selectBox = document.getElementById("employeeSelect");
        selectBox.innerHTML = "";
        // 遍历员工数组,创建下拉选项
        data.employees.forEach(employee => {
          const option = document.createElement("option");
          option.value = employee.id; // 员工ID作为选项值
          option.textContent = employee.name; // 员工名称作为显示文本
          selectBox.appendChild(option);
        });
        
        // 打开模态框
        modal.style.display = "block";
      })
      .catch(error => console.error('数据获取失败:', error));
  });
});

// 关闭模态框的逻辑
closeBtn.addEventListener("click", () => {
  modal.style.display = "none";
});
window.onclick = (event) => {
  if (event.target === modal) modal.style.display = "none";
}

3. 后端PHP逻辑(MySQL查询)

创建get_company_data.php文件,负责接收公司ID,查询公司信息和关联员工,返回JSON格式数据:

<?php
// 数据库连接配置,替换成你的实际信息
$servername = "localhost";
$dbUser = "你的数据库用户名";
$dbPwd = "你的数据库密码";
$dbName = "你的数据库名";

// 建立数据库连接
$conn = new mysqli($servername, $dbUser, $dbPwd, $dbName);
if ($conn->connect_error) {
  die("数据库连接失败: " . $conn->connect_error);
}

// 获取前端传递的公司ID
$companyId = $_GET['id'];

// 查询公司基本信息(用预处理语句防止SQL注入)
$companyStmt = $conn->prepare("SELECT id, name, address FROM companies WHERE id = ?");
$companyStmt->bind_param("i", $companyId);
$companyStmt->execute();
$companyData = $companyStmt->get_result()->fetch_assoc();

// 查询该公司的所有员工(假设员工表employees有company_id字段关联公司表)
$empStmt = $conn->prepare("SELECT id, name FROM employees WHERE company_id = ?");
$empStmt->bind_param("i", $companyId);
$empStmt->execute();
$empResult = $empStmt->get_result();
$employees = [];
while ($row = $empResult->fetch_assoc()) {
  $employees[] = $row;
}

// 返回JSON格式数据
echo json_encode([
  'company' => $companyData,
  'employees' => $employees
]);

// 关闭连接
$companyStmt->close();
$empStmt->close();
$conn->close();
?>

几个关键注意点

  • 数据库关联:确保员工表有company_id外键,和公司表的id字段关联,这样才能通过公司ID筛选出对应员工。
  • 安全防护:一定要用预处理语句做SQL查询,避免SQL注入风险,别直接把参数拼进SQL字符串里。
  • 模态框样式:上面的HTML没写模态框的CSS,你需要自己加基础样式(比如默认隐藏、半透明背景、居中布局等)才能让模态框正常显示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:57:36