【问题标题】:javascript async await Submitting a form with onsubmit using Promisejavascript async await 使用 Promise 提交带有 onsubmit 的表单
【发布时间】:2019-09-04 14:49:20
【问题描述】:

我有以下代码。

<!DOCTYPE html>
<html>
  <head>
    <script type="text/javascript">
      function sleep( lf_ms ) {
        return new Promise( resolve => setTimeout( resolve, lf_ms ) );
      }

      async function check_form() {
        alert( 'Test 1' );
        await sleep( 1000 );
        alert( 'Test 2' );

        return false;
      }
    </script>
  </head>
  <body>
    <form name="myform" method="post" action="test.htm" onsubmit="return check_form();">
      <input type="text" name="city"><br>
      <br>
      <a href="javascript:check_form();">check the method call via link</a><br>
      <br>
      <button type="submit">check the method call via submit button</button><br>
      <br>
    </form>
  </body>
</html>

我想让函数 check_form() 休眠 1 秒。

如果我点击链接,将显示“测试 1”和“测试 2”。如果我单击提交按钮,则仅显示“测试 1”。我在这里做错了什么?

我的问题与Submitting a form with submit() using Promise 不同。因为没有使用 javascript 事件处理程序 onsubmit。

【问题讨论】:

标签: javascript promise async-await onsubmit


【解决方案1】:

return check_form() 不会像您想象的那样返回 falseAsync functions 总是返回一个隐含的Promise,因此,您的表单仍然被提交。第一个alert 出现是因为到那时它仍然是同步的。 sleep 之后的所有内容都将安排在稍后的时间,并且不会等待表单提交。

要解决它,您可以调用该函数并然后返回false

function sleep(lf_ms) {
  return new Promise(resolve => setTimeout(resolve, lf_ms));
}

async function check_form() {
  console.log('Test 1');
  await sleep(1000);
  console.log('Test 2');
}
<form name="myform" method="post" onsubmit="check_form(); return false;">
  <input type="text" name="city"><br>
  <br>
  <a href="javascript:check_form();">check the method call via link</a><br>
  <br>
  <button type="submit">check the method call via submit button</button><br>
  <br>
</form>

编辑地址your comment

在函数 check_form 中检查用户输入。如果输入没有错误,则函数返回 true。如果有错误,该函数返回 false。发生错误时,不应该调用存储在标签表单的属性动作中的页面。

您不能像那样暂停 JavaScript,但您可以使用 return false 停止提交,然后在验证后通过 JavaScript 提交表单。

function sleep(lf_ms) {
  return new Promise(resolve => setTimeout(resolve, lf_ms));
}

async function check_form(form) {
  console.log('Test 1');
  await sleep(1000);
  console.log('Test 2');

  let city = document.getElementById('city').value;
  // Validation
  if (form !== undefined && city.trim() !== "") {
    // Validation succeeded, submit the form
    form.submit();
  }
}
<form name="myform" method="post" onsubmit="check_form(this); return false;">
  <input type="text" id="city" name="city"><br>
  <br>
  <a href="javascript:check_form();">check the method call via link</a><br>
  <br>
  <button type="submit">check the method call via submit button</button><br>
  <br>
</form>

【讨论】:

  • 感谢您的帮助和所有答案。现在可以了。
  • 此答案禁用默认浏览器表单验证。对于某些用例来说,维护默认的浏览器表单验证可能很重要
猜你喜欢
  • 2018-05-18
  • 2012-11-22
  • 2020-04-29
  • 2021-05-13
  • 2023-03-10
  • 2013-03-13
  • 1970-01-01
  • 1970-01-01
  • 2015-11-13
相关资源
最近更新 更多