在列表頁點擊「刪除」鏈接時,彈出瀏覽器原生確認對話框,用戶點擊「確定」才發起刪除請求,點擊「取消」則中止操作。這是最基礎的前端攔截機制,無需引入任何 JS 庫。
刪除
關鍵點:return del() 的返回值決定鏈接是否跳轉。del() 返回 true 繼續跳轉,返回 false 阻止默認行為。
可簡寫為一行:function del() { return confirm("確定要刪除嗎?"); }
_request('id'); // 兼容 GET/POST
if ($id) {
$user = M('user');
$result = $user->where(['id' => $id])->delete();
if ($result !== false) {
$this->success('刪除成功!');
} else {
$this->error('刪除失敗!');
}
} else {
$this->error('參數錯誤!');
}
}
?>
刪除
刪除屬於狀態修改操作,必須驗證 Token:
// 表單方式(推薦)// 控制器 if ($this->validateToken()) { // 執行刪除 }
$('.btn-delete').click(function(e) {
e.preventDefault();
const id = $(this).data('id');
if (confirm('確定刪除?')) {
$.post('{:U("shanchu")}', {id: id, __TOKEN__: '{:sp_get_token()}'}, function(res) {
if (res.code === 1) {
$(`tr[data-id="${id}"]`).fadeOut();
} else {
alert(res.msg);
}
}, 'json');
}
});
最簡單的實現:onclick="return confirm('...')" 即可滿足基本需求。生產環境建議:POST 請求 + Token 驗證 + AJAX 異步 + 友好提示組件,兼顧安全性與用戶體驗。