
本文详解如何在前端点击座椅图片时,动态获取其位置标识(如 pos1、pos2),并通过 fetch api 以 post 方式将该编号提交给 php 脚本,实现前后端数据联动,避免页面跳转丢失状态。
本文详解如何在前端点击座椅图片时,动态获取其位置标识(如 pos1、pos2),并通过 fetch api 以 post 方式将该编号提交给 php 脚本,实现前后端数据联动,避免页面跳转丢失状态。
在构建类似公交/宴会座位选择系统时,仅靠前端交互(如 confirm() 提示)无法持久化用户选择——一旦跳转到 paymethod.php,原始选中信息即丢失。正确做法是:在用户点击座椅时捕获其唯一标识,并异步提交至 PHP 后端存储或校验,后续页面(如支付页)再通过会话($_SESSION)或数据库读取该值。
✅ 推荐方案:使用 Fetch API 发送 POST 请求
你已在 getChairs() 中熟练使用 fetch() 获取座位占用状态,延续该模式发送选中数据最为自然、现代且无需额外依赖。
步骤一:增强点击事件,提取座位编号
修改 .chair 的点击逻辑,不再调用 checker() 弹窗,而是先捕获并提交数据:
$(".chair").on("click", function() { const $this = $(this); const classList = $this.attr("class"); // e.g. "chair pos3" const match = classList.match(/pos(d+)/); const chairId = match ? match[1] : null; if (!chairId) { alert("无效座位,请重试"); return; } // 异步提交至 PHP fetch("code/save_seat.php", { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded", }, body: `seat_id=${encodeURIComponent(chairId)}` }) .then(response => response.json()) .then(data => { if (data.success) { alert(`已成功选择座位 ${chairId}!`); // 可选:跳转前设置 sessionStorage 或更新 UI 状态 sessionStorage.setItem("selectedSeat", chairId); window.location.href = "paymethod.php"; } else { throw new Error(data.message || "保存失败"); } }) .catch(err => { console.error("提交座位失败:", err); alert("网络错误,请检查后重试"); }); });
步骤二:编写接收端 PHP 脚本(code/save_seat.php)
<?php session_start(); header('Content-Type: application/json'); if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !isset($_POST['seat_id'])) { echo json_encode(['success' => false, 'message' => '缺少 seat_id']); exit; } $seatId = filter_input(INPUT_POST, 'seat_id', FILTER_SANITIZE_NUMBER_INT); if (!$seatId || $seatId < 1) { echo json_encode(['success' => false, 'message' => '座位编号无效']); exit; } // ✅ 安全存储:写入 SESSION(适用于单次会话) $_SESSION['selected_seat_id'] = (int)$seatId; // ? 进阶建议:若需多设备/多用户隔离,应结合用户 ID 写入数据库 // $pdo->prepare("INSERT INTO bookings (user_id, seat_id, created_at) VALUES (?, ?, NOW())")->execute([$userId, $seatId]); echo json_encode(['success' => true, 'seat_id' => $seatId]); ?>
步骤三:在 paymethod.php 中读取选中座位
<?php session_start(); $selectedSeat = $_SESSION['selected_seat_id'] ?? null; if (!$selectedSeat) { header("Location: seat_selection.php"); exit; } // 后续可基于 $selectedSeat 查询价格、生成订单等 ?>
⚠️ 关键注意事项
- 不要依赖 onclick=”checker()” 内联事件:它无法访问当前元素上下文(如 this.className),且与 jquery 事件处理混用易导致逻辑冲突。统一使用 $(“.chair”).on(“click”, …)。
- 始终验证与过滤输入:PHP 端必须使用 filter_input() 或 intval() 处理传入的 seat_id,杜绝注入风险。
- 避免重复提交:可在提交后禁用按钮或添加加载态(如 $(this).prop(“disabled”, true)),防止用户连点。
- 兼容性兜底:Fetch API 在 IE 中不支持,若需兼容旧浏览器,可改用 XMLHttpRequest 或引入 whatwg-fetch polyfill。
通过以上结构化实现,你不仅解决了“传递座位编号”的核心需求,更构建了可扩展、可维护、符合 Web 最佳实践的前后端通信链路。
立即学习“PHP免费学习笔记(深入)”;