微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript在then块中提交表单并使用swal从非异步函数返回false

如何解决javascript在then块中提交表单并使用swal从非异步函数返回false

我正在尝试使用 onsubmit return myFunc() 提交表单,但我也想在函数内使用 swall。这是我的代码的样子。 <form action="./script.PHP" onsubmit"return myFunc()"> </form>

let userName = $("#userName")
// use some validation here and finally

swal({
     title: "Are you sure",text: "Some Text"
     buttons: ['No','Yes']
     }).then((result) { 
         if(result) {
              console.log("Here we are!! ")
              return true
             // This is when I want the form to be submitted other wise return false
         } else {return false}        
    })
return false;
}    

发生的情况是函数返回 false 并且从不执​​行 .then 块中的代码

解决方法

代码中有一些语法错误。 function 参数中缺少 => 关键字或 then,并且 swal() 的参数列表中缺少逗号。除此之外,混合同步和异步任务时逻辑不起作用。

实际的事件监听器是 onsubmit 属性的内容,它调用 myFunc 并将该函数返回的值返回给内部事件处理程序。 swal() 调用返回一个承诺,然后在传递给 then 的回调函数中进行处理。 swal 调用因此是异步的,回调函数在用户真正点击警报框中的按钮后执行。那个时候myFunc已经完成返回false

要解决此问题,您必须在所有情况下阻止表单提交的默认操作,如果 swal 结果为“是”,则在传递给 {{1 的回调函数中提交表单}}。像这样:

then
const form = document.querySelector('#form');

function myFunc(e) {
  e.preventDefault(); // Prevent the form submission in any case
  swal({
    title: "Are you sure",text: "Some Text",buttons: ['No','Yes']
  }).then((result) => {
    if (result) {
      console.log('Submit the form.')
      // form.submit(); // Uncomment this line to submit the form     
    } else {
      console.log('No submission.')
    }
  });
}

form.addEventListener('submit',myFunc);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。