PHP中为href删除按钮添加sweetalert2确认弹窗无需JSON数据
问题原因
你的代码存在3个核心问题导致确认后不执行删除:
- 选择器不匹配:按钮定义用的是
id="btnDelete",但JS用了类选择器$('.btnDelete'),如果是列表页多个删除按钮的话,id属性不能重复,要改成class属性 <button>标签原生不支持href属性,就算写了也不会自动触发跳转,需要手动获取href值执行删除逻辑- 弹窗确认的
then回调里没有写实际执行删除的代码,现在只是弹了成功提示,没有调用删除接口或者跳转
修复方案
第一步:先修改HTML代码
把按钮的id改成class,避免多删除按钮时id冲突:
<button type="button" class="btn btn-danger fa fa-trash but btnDelete" href="<?php echo site_url('administrator/master/delete/' . $a->idDept); ?>" data-toggle="tooltip" data-placement="top" title="Delete"></button>
第二步:选择对应JS方案修改
方案1:跳转执行删除(适合删除后需要刷新列表的场景)
$('.btnDelete').click(function() { // 获取当前按钮对应的删除地址 const deleteUrl = $(this).attr('href'); Swal.fire({ title: 'Are you sure?', text: "It will permanently deleted !", icon: 'warning', // 新版本SweetAlert2用icon代替type参数,旧版本可改回type showCancelButton: true, confirmButtonColor: '#3085d6', cancelButtonColor: '#d33', confirmButtonText: 'Yes, delete it!' }).then((result) => { // 判断用户是否点击了确认按钮 if (result.isConfirmed) { // 跳转到删除地址执行操作 window.location.href = deleteUrl; } }); });
方案2:AJAX无刷新删除(体验更好,不需要刷新页面)
$('.btnDelete').click(function() { const deleteUrl = $(this).attr('href'); // 缓存当前按钮对象,删除成功后可以移除对应列表行 const $currentBtn = $(this); Swal.fire({ title: 'Are you sure?', text: "It will permanently deleted !", icon: 'warning', showCancelButton: true, confirmButtonColor: '#3085d6', cancelButtonColor: '#d33', confirmButtonText: 'Yes, delete it!' }).then((result) => { if (result.isConfirmed) { $.get(deleteUrl, function(res) { Swal.fire( 'Deleted!', 'Your file has been deleted.', 'success' ); // 示例:删除成功后移除当前按钮所在的表格行,可根据自己的页面结构调整 $currentBtn.closest('tr').remove(); }).fail(function() { Swal.fire( 'Error!', 'Delete failed, please try again later.', 'error' ); }); } }); });
注意事项
- 推荐删除接口用POST请求搭配CSRF校验,不要用GET请求,避免爬虫误爬、浏览器预加载触发误删
- 如果用跳转方案,删除接口处理完成后可以跳转回列表页,在列表页加载时弹出删除成功提示
内容的提问来源于stack exchange,提问作者RezNov
相关产品推荐
相关产品推荐

