如何在CodeIgniter中结合PHP表单使用SweetAlert2并解决提交跳转问题?
解决CodeIgniter中SweetAlert2确认后再提交表单的问题
嘿,我明白你遇到的困扰了——表单一点提交就直接跳转,完全没等SweetAlert2的确认弹窗发挥作用对吧?这是因为浏览器默认的表单提交行为没被拦截,咱们得用JavaScript把这个流程改一改,让用户确认后再触发真正的提交。
下面是具体的解决步骤,你可以照着来:
1. 给表单加个唯一ID
首先,在CodeIgniter的form_open函数里给表单加个ID,这样JS能精准定位到它:
<?= form_open('你的控制器/处理方法', ['id' => 'confirmSubmitForm']) ?> <!-- 这里放你的表单字段,比如用户名、邮箱这些 --> <div class="form-group"> <label for="username">用户名</label> <input type="text" name="username" id="username" required> </div> <div class="form-group"> <label for="email">邮箱</label> <input type="email" name="email" id="email" required> </div> <button type="submit" class="btn btn-success">提交表单</button> <?= form_close() ?>
2. 引入SweetAlert2(如果还没加的话)
确保页面里已经引入了SweetAlert2的脚本,你可以用CDN放在页面底部:
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
3. 写拦截提交的JavaScript代码
接下来是核心逻辑:阻止表单默认提交,弹出确认框,用户确认后再手动提交表单。把这段JS放在表单之后或者页面的脚本区域:
// 监听表单的提交事件 document.getElementById('confirmSubmitForm').addEventListener('submit', function(e) { // 先阻止浏览器默认的提交行为,这样就不会直接跳转了 e.preventDefault(); // 把当前表单对象存起来,方便后面调用 const targetForm = this; // 弹出SweetAlert2确认弹窗 Swal.fire({ title: '确认提交?', text: '你确定要提交这份数据吗?提交后无法撤回哦', icon: 'warning', showCancelButton: true, confirmButtonColor: '#3085d6', cancelButtonColor: '#d33', confirmButtonText: '是的,提交!', cancelButtonText: '再想想' }).then((result) => { // 如果用户点击了确认按钮 if (result.isConfirmed) { // 手动触发表单提交,这时候才会真正把数据发给CodeIgniter的控制器 targetForm.submit(); } }); });
额外说明
- 如果你项目里用了jQuery,也可以这么写:
$('#confirmSubmitForm').on('submit', function(e) { e.preventDefault(); const form = $(this)[0]; // 转成原生DOM对象 Swal.fire({ // 弹窗配置和上面一致即可 }).then((result) => { if (result.isConfirmed) { form.submit(); } }); });
- 不用担心CodeIgniter的CSRF令牌,手动提交表单会自动带上所有隐藏字段(包括CSRF的那个),不会有验证问题。
- 如果还是有问题,打开浏览器的开发者工具(F12)看控制台有没有JS报错,比如表单ID拼写错了,或者SweetAlert2没加载成功。
内容的提问来源于stack exchange,提问作者aitizazsyed02
相关产品推荐
相关产品推荐

