由于 javascript(包括表单提交)是同步和单线程模型,除了 ajax 调用。那正确吗?但我正面临一个问题。
我在第 1 行提交表单,然后关闭弹出窗口。发生的事情是 self.close 在表单提交之前被调用。 所以这里它在异步模式下运行。表单提交是异步过程吗?如果是的话我怎么能在之后制作代码 表单提交同步?(我不想使用 setTimeOut 和 ajax)
这是我的相关jsp代码
function clickSave()
{
document.form.action="customerAction.do";
document.form.submit();// line 1
self.close();// line 2
}
更新:- 看来我需要更正自己的表单提交是按照 Is form submit synchronous or async? 的异步过程.所以问题是我怎样才能使 self.close 与表单提交同步
最佳答案
As javascript(including form submission) is synchronous and single thread model except ajax calls. Is that right? But i am facing one issue regarding this.
嗯,JS对每一个事件监听器都是异步的。 Ajax 允许异步模式,将结果作为事件返回。
JS 大多是不并发的:一次只执行一个函数。但是,在最新版本中,有一些方法可以在 JS 中创建后台“并发”线程 (1)
JS 在单线程上运行。 (后台线程除外)
I am submitting the form at line 1 and then closing the pop up. what happens is self.close get called before form submission.
那是不可能的。
Is form submission an asynchronous process?
提交是异步的,即JS会一直运行到结束。
你可以测试这个例子(2)。
If yes how can i make the code after form submission synchronous?(I dont want to use setTimeOut and ajax)
提交将重新加载整个页面,因此您的 JS 将结束,之后,窗口将使用表单结果从服务器加载新页面。您可以在此新页面中包含一个新的 JS 以“继续”。
如果您不想重新加载所有页面,您必须使用 AJAX,在这种情况下,您有 2 个选择:
- 异步:您可以设置一个事件监听器来接收和使用结果。
- 同步:您的页面将阻塞,直到结果准备就绪。
(2):
<html>
<body>
<script type="text/javascript">
function click2()
{
document.getElementById('form1').submit();
for(var i=0; i < 1000000000; i++);
window.open('http://www.stackoverflow.com');
}
</script>
<button onclick="click2();"> click </button>
<br/><br/>
<form id="form1" action="http://www.duckduckgo.com" method="get">
<input type="text" value="hello"/>
</form>
</body>
</html>
关于javascript - 如何使表单提交同步?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17188149/