How to make form submission synchronous?

2019-02-18 05:18发布

问题:

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.

I am submitting the form at line 1 and then closing the pop up. what happens is self.close get called before form submission. So here it is behaving in asynch mode. Is form submission a asynchronous process? If yes how can i make the code after form submission synchronous?(I dont want to use setTimeOut and ajax)

Here is my relevant jsp code

function clickSave()
 {

    document.form.action="customerAction.do";
    document.form.submit();// line 1
    self.close();// line 2

 }

Update:- Looks like i need to correct myself form submission is asynchronous process as per Is form submit synchronous or async?. So question is how can i make self.close synchronous with form submission

回答1:

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.

Well, JS is asynchronous for every event listener. Ajax allow asynchronous mode, returning the result as an event.

JS is mostly NOT CONCURRENT: only one function is being performed at time. Overwere, in newest versions there is ways to create background "concurrent" JS (1)

JS run on a single thread. (except for background 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.

That is not possible.

Is form submission a asynchronous process?

The submission is asynchronous, that is, the JS will continue to run and end.

You may test that will this example (2).

If yes how can i make the code after form submission synchronous?(I dont want to use setTimeOut and ajax)

Submit will reload the entire page, so your JS will end and after that, the window will load the new page from the server with the form result. You may include in this new page a new JS to "continue".

If you don't want to reload all the page, you must use AJAX, and in this case, you have 2 options:

  • Asynchronous: you may set an event listener to receive and use the result.
  • Synchronous: your page will block until the result is ready.

Note: (1): https://developer.mozilla.org/en-US/docs/Web/Guide/Performance/Using_web_workers?redirectlocale=en-US&redirectslug=DOM%2FUsing_web_workers

(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>