Laravel 9 结合SweetAlert实现删除确认功能失效求助
Laravel 9 + SweetAlert 删除功能问题排查与修复
核心问题点
- 控制器代码顺序错误:
Alert::toast写在return redirect()之后,代码执行到return就终止,永远不会触发提示;且AJAX请求不需要跳转,应返回JSON响应。 - AJAX参数拼写错误:
Method应为小写的method,JavaScript对大小写敏感,大写会导致请求默认用GET,不符合destroy路由的DELETE要求。 - AJAX参数位置错误:
dataType和contentType被错误放在data对象里,需作为AJAX的顶层配置参数。 - SweetAlert回调逻辑混淆:变量名
willCancel逻辑反了,用户点击「确认删除」时回调接收的值为true,当前判断逻辑会搞反操作。
修正后的代码
控制器(EmployeeController.php)
public function destroy($id) { Employee::findorFail($id)->delete(); // AJAX请求返回JSON响应 return response()->json([ 'success' => true, 'message' => 'Employee has been deleted successfully' ]); // 如需兼容非AJAX请求,可添加判断: // if(request()->ajax()) { // return response()->json([...]); // } else { // Alert::toast('Employee has been deleted successfully', 'success'); // return redirect()->route('employee.index'); // } }
Blade视图
<a href="{{ route('employee.destroy', $item->id) }}" onclick="confirmation(event)">Delete</a>
JavaScript脚本
<script> function confirmation(ev) { ev.preventDefault(); var urlToRedirect = ev.currentTarget.getAttribute('href'); swal({ title: "Are you sure to delete this employee?", text: "You will not be able to revert this!", icon: "warning", buttons: true, dangerMode: true, }) .then((willDelete) => { // 点击确认删除时执行AJAX请求 if (willDelete) { $.ajaxSetup({ headers: { "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content"), }, }); $.ajax({ method: "DELETE", // 修正为小写method url: urlToRedirect, dataType: 'json', // 移到顶层配置 contentType: 'application/json', // 移到顶层配置 success: function(data) { // 成功提示后刷新页面 swal(data.message, { icon: "success" }).then(() => { location.reload(); }); // 可选:局部删除DOM元素,无需刷新页面 // ev.currentTarget.closest('tr').remove(); }, error: function() { swal("Error!", "Failed to delete the employee.", "error"); } }); } }); } </script>
额外注意事项
- 确保页面已正确引入 jQuery 和 SweetAlert2 的资源文件,否则脚本无法运行。
- 确认路由配置中已注册资源路由:
Route::resource('employee', EmployeeController::class);,保证destroy路由的请求方法为DELETE。
内容的提问来源于stack exchange,提问作者Reman Bala
相关产品推荐
相关产品推荐

