不使用jQuery如何将HTML表格的SQL变量传到JS弹窗再转为PHP变量
工单核销功能修改方案
核心修改点
- 给按钮点击事件添加工单ID传参
- 弹窗表单新增隐藏域存储选中的工单ID
- 调整删除逻辑,接收表单提交的ID执行删除,避免SQL注入
调整后的完整代码
<!DOCTYPE html> <html> <head> <script> // 接收传过来的工单ID,存入隐藏域后显示弹窗 function complete(requestId) { // 给隐藏域赋值 document.getElementById("deleteId").value = requestId; document.getElementById("myForm").style.display = "block"; } function closeForm() { document.getElementById("myForm").style.display = "none"; } </script> <link rel="stylesheet" href="styles.css"> <title>KCHC Work Orders</title> </head> <?php $host = "localhost"; $user = ""; // 填写你的数据库账号 $password = ""; // 填写你的数据库密码 $database = "workorders"; $DBConnect = @new mysqli($host, $user, $password, $database); if ($DBConnect->connect_error) { echo "The database server is not available at the moment. " . "Connect Error is " . $DBConnect->connect_errno . " " . $DBConnect->connect_error . "."; } // 表单提交时执行删除逻辑 if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_id'])) { $deleteId = $_POST['delete_id']; // 使用预处理语句避免SQL注入 $stmt = $DBConnect->prepare("DELETE FROM requests WHERE request_id = ?"); $stmt->bind_param("i", $deleteId); $stmt->execute(); $stmt->close(); // 删除后刷新页面更新表格 header("Location: ".$_SERVER['PHP_SELF']); exit; } ?> <header> <div class="menu"> <nav> <a href="orderform.php">Create a Request</a> </nav> </div> </header> <body> <?php $sql = "SELECT request_id, name, date, location, description FROM requests"; $stmt = $DBConnect->query($sql); if ($stmt->num_rows > 0) { echo '<div class="request_box">'; echo '<table id="myTable" ><tr><th>ID</th> <th>Name</th> <th>Date</th> <th>Location</th> <th>Description</th> <th>Complete?</th> </tr>'; while ($Row = $stmt->fetch_assoc()) { // 按钮点击时传入当前工单ID echo "<tr id='".$Row['request_id']."'>"; echo "<th>" . $Row['request_id'] . "</th> <th>" . $Row['name'] . "</th> <th>" . $Row['date'] . "</th> <th>" . $Row['location'] . "</th> <th>" . $Row['description'] . "</th> <th><input type='button' onclick='complete(".$Row["request_id"].")' value='完成' /></th> </tr>"; } echo "</table> </div>"; } else { echo '<div class="request_error">'; echo "<p> There are no jobs to complete!</p> <br>"; echo "<p> If you think there should be, please contact Matt or his genius son</p>"; echo '</div>'; } ?> <div class="popup" id="myForm" > <form id="formReal" method="post"> <!-- 隐藏域存储要删除的工单ID --> <input type="hidden" id="deleteId" name="delete_id" value=""> <h1>Would you like to remove this job? </h1> <input type="submit" class="btn" value="Remove from List" /> <button type="button" class="btnCancel" onclick="closeForm()">Cancel</button> </form> </div> </body> </html>
逻辑说明
- 点击表格行的「完成」按钮时,会把当前行的工单ID传给JS的
complete函数 - JS函数将ID存入表单的隐藏域后弹出确认弹窗
- 用户确认删除后,表单会把ID提交给后端PHP
- 后端接收ID后用预处理语句执行删除操作,完成后刷新页面更新工单列表
内容的提问来源于stack exchange,提问作者Jake Ives
相关产品推荐
相关产品推荐

