JSP 表格每行有「刪除」按鈕,點擊無反應。控制台輸出 `user.getId()` 顯示異常值,推測隱藏域 `` 未正確綁定或提交時未包含目標行 ID。
<c:forEach items="${userList}" var="user">
<tr>
<td>${user.name}</td>
<td>${user.email}</td>
<td>
<form action="${pageContext.request.contextPath}/user/delete" method="post">
<input type="hidden" name="id" value="${user.id}" />
<button type="submit" class="btn btn-danger btn-sm"
onclick="return confirm('確定刪除 ${user.name} 嗎?')">
刪除
</button>
</form>
</td>
</tr>
</c:forEach>
關鍵點:
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@PostMapping("/delete")
public String delete(@RequestParam("id") Long id, RedirectAttributes ra) {
try {
userService.deleteById(id); // 數據庫物理刪除或邏輯刪除
ra.addFlashAttribute("msg", "刪除成功");
} catch (Exception e) {
ra.addFlashAttribute("msg", "刪除失敗:" + e.getMessage());
}
return "redirect:/user/list"; // 重定向回列表頁,防止表單重復提交
}
}
@Service
@Transactional
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper; // MyBatis/JPA
@Override
public void deleteById(Long id) {
// 1. 可選:檢查關聯數據(訂單、日誌等),決定物理刪除/邏輯刪除/拋異常
// 2. 執行刪除
userMapper.deleteById(id); // 或 userRepository.deleteById(id)
}
}
<button type="button" class="btn btn-danger btn-sm delete-btn" data-id="${user.id}">刪除</button>
$('#userTable').on('click', '.delete-btn', function() {
var $btn = $(this);
var id = $btn.data('id');
var $row = $btn.closest('tr');
if (!confirm('確定刪除該用戶嗎?')) return;
$.post('/user/delete', { id: id }, function(resp) {
if (resp.success) {
$row.fadeOut(300, function() { $(this).remove(); });
showMsg('刪除成功');
} else {
showMsg('刪除失敗:' + resp.msg);
}
}).fail(function() { showMsg('網絡錯誤'); });
});
@PostMapping("/delete")
@ResponseBody
public Map deleteAjax(@RequestParam("id") Long id) {
Map result = new HashMap<>();
try {
userService.deleteById(id);
result.put("success", true);
} catch (Exception e) {
result.put("success", false);
result.put("msg", e.getMessage());
}
return result;
}
| 現象 | 原因 | 修復 |
|---|---|---|
| 刪除按鈕無反應 | 按鈕不在 ` | 放入 form + type=submit,或綁定 AJAX 點擊事件 |
| 後端收到 id 為 null | 隱藏域 `name` 不匹配參數名,或表單未包含該隱藏域 | 檢查 `name="id"` 與 `@RequestParam("id")` 一致;每行獨立 form |
| 刪除後頁面未更新 | 同步提交未重定向,或 AJAX 未移除行 DOM | 控制器 `redirect:/list`;AJAX 成功回調中 `$row.remove()` |
| 誤刪其他行 | 全表單只有一個隱藏域,值為最後一行 ID | **每行一個 form**,或 AJAX 取 `data-id` |
表格刪除核心在於 **「每行獨立提交上下文(ID)」**。傳統同步方式:**每行一個 `