You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel5.8使用SweetAlert确认后调用form.submit()不执行表单action如何解决

问题原因
  • 冲突的提交逻辑:没有移除checkbox元素上原有的onchange="this.form.submit();"属性,新增的点击事件和原有onchange事件逻辑冲突,导致提交行为异常。
  • 阻止默认行为导致状态丢失:点击事件中调用e.preventDefault()会直接阻止checkbox默认的选中/取消选中状态更新,就算后续触发表单提交,wallet_checked字段也不会携带正确的勾选值,甚至不会被包含在提交参数中。
  • SweetAlert回调判断错误:如果你使用的是SweetAlert2版本,then回调返回的是一个包含value属性的对象,而非直接的布尔值,原代码的if(isConfirm)判断逻辑无效,不会触发正确的提交分支。
解决方案

步骤1:修改表单代码,移除冗余的onchange属性

<form id="myForm" action="{{ route('acceptWallet') }}" method="POST">
   @csrf
   <!-- 删掉原来的onchange属性 -->
   <input type="checkbox" id="btn-submit" name="wallet_checked">
</form> 

步骤2:修改JS逻辑,修正事件触发和判断逻辑

改用change事件监听checkbox状态变化,先保存勾选状态再弹确认框,确认后再提交表单:

$(document).on('change', '#btn-submit', function(e) {
    e.preventDefault();
    // 保存当前勾选状态
    const isChecked = $(this).is(':checked');
    const form = $(this).closest('form');

    swal({
        title: "Attention!",
        text: "Are you sure you want to make this transaction",
        type: "warning",
        allowEscapeKey: false,
        allowOutsideClick: false,
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "Yes",
        cancelButtonText: "No",
        showLoaderOnConfirm: true,
        closeOnConfirm: false
    }).then((result) => {
        // SweetAlert2 用result.value判断是否点击确认
        // 如果是SweetAlert1版本,这里直接判断if(result)即可
        if (result.value) {
            // 手动同步checkbox状态
            $(this).prop('checked', isChecked);
            form.submit();
        } else {
            // 取消操作回滚checkbox状态
            $(this).prop('checked', !isChecked);
        }
    });
});

可选排查方案

如果修改后仍然异常,可以打开浏览器开发者工具的「网络」面板,提交时检查:

  • 请求方法是否为POST
  • 请求地址是否和acceptWallet路由匹配
  • 请求参数中是否包含_token和wallet_checked字段

内容的提问来源于stack exchange,提问作者user16723850

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 19:00:01