Is js executed after form synchronized submit

2019-06-01 11:08发布

问题:

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.

回答1:

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.