表单同步提交后,js是否被执行 [英] Is js executed after form synchronized submit

查看:130
本文介绍了表单同步提交后,js是否被执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码如下:

  form.submit(); //同步提交,不是异步,表单是不是html表单,而是由javascript 
创建的一些代码; //这行是执行的,还是有时执行的有时不是

我有第2行的一些统计代码(发送一个http请求到服务器),并且真正获得一些数据。由于统计数据和期望值之间存在很大差距,我怀疑第2行总是执行。

解决方案

这取决于什么表单在提交时执行:


  • 如果表单正常提交,那么代码可以运行。标准表单提交将浏览器重定向到action属性中定义的url。代码可能会运行,但页面已经准备离开,因此您可能不会看到 form.submit()之后的代码是什么。


  • 如果表单提交并被JavaScript捕获(可能通过事件处理程序),那么 form.submit() 可以运行,但取决于该事件处理程序的功能。如果处理程序不阻止正常的表单提交,那么情况与第一个相同。如果处理程序阻止正常的表单提交,那么它可以运行。




我建议您为该表单构建一个处理程序,使用像 return false 和/或 event.preventDefault()这样的技术来阻止正常的表单提交,并且运行代码还有。

my code is as following:

form.submit();//synchronized submit, not asynchronous,the form is not a html form but created by javascript
some codes here;//Is this line executed, or it sometimes executed sometimes not

I have some statistics code(send a http request to a server) in 2rd line and really get some data. Because there is a big gap between the statistic data and expected, I doubt 2rd line is always executed.

解决方案

It depends on what the form does on submit:

  • If the form submits normally, then the code may run. Normal form submission redirects the browser to the url defined in the action attribute. The code may run but the page is already preparing to leave thus you may not see what the code after form.submit() does.

  • If the form submits and is caught by JavaScript (maybe by an event handler), then the code after form.submit() could run but depends on what that event handler does. If the handler does not prevent normal form submission, then the situation is the same as the first. If the handler prevents normal form submission, then it can run.

I suggest you build a handler for that form that prevents normal form submission using techniques like return false and/or event.preventDefault() and also, run the code in there as well.

这篇关于表单同步提交后,js是否被执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆