简体   繁体   中英

when form submit ,the order of click function and submit

about click and submit example below:

<form action="url" method="post">
<input type="text" id="input1"/>
<input type="submit" value="submit" onclick="testFun()"/>
</form>

if it is possible that function testFun run after the form's submit when we click the button to submit

if the answser is no. why? how does the browser work when click the submit button?? the order is click function-> submit ? is right??

No you cannot execute a function after the form has been submitted - the order of which things are executed is as follows :

  • User clicks the submit button
  • The onclick function is executed
  • The browser submits the page to the url specified in the action of the form

You can prevent the browser submitting the page by returning false from the onclick handler :

function myfunc() {
  // do some stuff
  return false;
}

the submit button should then be modified like this :

<input type="submit" onclick="return myfunc()"/>

If you do wish to execute a function after the form has been submitted you need to submit the form using AJAX - this doesnt cause the browser to navigate away from the page and a JavaScript function can be executed after the form has been submitted

This is not possible because the form's action would redirect the browser to that URL.

1 option would be to run testFun() on your action url page, but this might not be possible depending on what the function does.

If you are to post more information about what you are actually trying to do here, then it might help.

不,但testFun可能(反过来)调用另一个异步函数,该函数在表单提交之前不会运行(此时它根本不会运行,因为浏览器会离开页面)。

No it is not possible, after submit you are out of the scope from the current page. But if you are using an iframe for your form submit and call the function on the parent page, then I thought it will work.

The anwswer is "It is not possible"

Why

Because once the browser triggers the submit event all user interaction with page is stopped. After the submit event is triggered the communication is between your browser and the webserver. This is how broswers are designed.

In your case Form submission happens because you have a form in your page and in that form you have an input of type=button. If you dont want to submit the page you can change the type of the input to button.

Check this fiddle http://jsfiddle.net/kiranvj/MBxNs/1/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM