Rüd*_*idt 3 javascript onsubmit promise async-await
我有以下代码。
<!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>
Run Code Online (Sandbox Code Playgroud)
我想让函数 check_form() 休眠 1 秒钟。
如果我单击链接,将显示“测试 1”和“测试 2”。如果我单击提交按钮,则只显示“测试 1”。我在这里做错了什么?
我的问题与使用 Promise 使用 submit() 提交表单不同。因为未使用 javascript 事件处理程序 onsubmit。
return check_form()不会false像您想象的那样返回。异步函数总是返回一个隐式的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');
}Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
编辑以解决您的评论
在函数 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();
}
}Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11847 次 |
| 最近记录: |