开发者

how to wait for asynchronous operation on form onsumbit

I've added a hook to form submit event (there are other events on开发者_如何学JAVA the form submit ) and need to report the submit to a server on another domain using createlement(script).

How can I cause the submit function to wait to make sure the createlement(script) has successfully accessed the server ?


How about something like this:

<script>
  function handleSubmit(form) {
    doSomethingAsynchron(
       function() { // callback function
          form.submit();
       }
    );
    return false;
  }
</script>

<form onsubmit="return handleSubmit(this);" ... >
...
</form>


Try to make use of JavaScript events. You can register any function to be called when a certain event occurs. Either utilise some of the predefined events to signal the completion of your code or use something like some Yahoo! library to create custom events which could represent the completion of the server request (found the last one with a short Google search, but looks promising).

I expected JS to have a built-in custom event architecture but obviously it has not. Thus you need to use external libraries like this Yahoo! thing. Maybe this changes in the near future. This is above my knowledge. But I can surely recommend using events because they solve exactly the problem you described.

(Alternatively you can do busy wait like Thariama described. Either with sleep cycles or not busy waiting in general is discouraged where possible.)

Illustration:

<script>
// register function b() for custom event

function a() {
    //upload
    // (takes time... but no busy wait)

    //fire custom event
}

function b() {
    //do some other code
}
</script>

<body>

<form onsubmit="a()">
</form>

</body>


A not very elegant solution would be to use a time interval to check if the script to has acsessed the server (check the response). For this use setInterval.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜