form.submit();不 运行 表格动作

form.submit(); does not run action of form

我有一个使用 sweetalert.js 的 Laravel 5.8 项目。

我有这样的表格:

<form id="myForm" action="{{ route('acceptWallet') }}" method="POST">
   @csrf
   <input type="checkbox" id="btn-submit" name="wallet_checked" onchange="this.form.submit();">
</form> 

然后,这是路线 acceptWallet:

Route::post('course/accept/wallet','Wallet\WalletController@acceptWallet')->name('acceptWallet');

并且在 WalletController 的方法 acceptWallet 中,我添加了这个:

public function acceptWallet(Request $request)
{
     dd($request->wallet_checked);
}

如您所见,我使用 onchange="this.form.submit();" 提交了表单,但没有使用提交按钮,而且效果很好。

然后通过使用此脚本,我尝试显示 SweetAlert 确认消息框,其中包含 YesNo 作为按钮:

$(document).on('click', '#btn-submit', function(e) {
    e.preventDefault();
    let form = $(this).parents('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((isConfirm) => {
        if (isConfirm) {
            form.submit();
            return true;
        }
        return false;
    });
});

如您所见,如果用户单击 按钮以提交表单,我已使用 form.submit();

但现在的问题是,表单没有提交,只是刷新页面,结果没有显示 dd($request->wallet_checked);

那么这里出了什么问题?如何在显示 SweetAlert 弹出消息后正确提交表单?

我也试过 document.forms['myForm'].submit(); 而不是 form.submit(); 但没有提交表格。

可能是您的 let form = $(this).parents('form'); 没有正确找到表格。所以只是 console.log(form) 并检查它是否可用。

此外,由于您的表单有一个 ID,您可以执行如下操作。

}).then((isConfirm) => {
    if (isConfirm) {
        document.getElementById("myForm").submit();
       //Or $('#myForm').submit();
        return true;
    }
    return false;
});

或者通过 id

开玩笑地用 jquery 创建变量
let form =  $('#myForm')