开发者

onBeforeUnload and multiple forms

开发者 https://www.devze.com 2022-12-22 06:53 出处:网络
I want to have a feature to submit several forms开发者_Python百科 on a page when the user leaves the page. There is this \"do you wanna save?\" question and my code so far is like this:

I want to have a feature to submit several forms开发者_Python百科 on a page when the user leaves the page. There is this "do you wanna save?" question and my code so far is like this:

function checkForChanges( ) {
  if (window.formform1Changed == true) {
    if (window.asked == false) {
      window.asked=true;
      doSave = confirm("Wanna save? Click OK")
    }
    if (window.doSaveForms || doSave) {
      window.doSaveForms = true;
      document.forms.form1.submit();
    }
  }
  if (window.formform2Changed == true) {
    if (window.asked == false) {
      window.asked=true;
      doSave = confirm("Wanna save? Click OK.")
    }
    if (window.doSaveForms || doSave) {
      window.doSaveForms = true;
      document.forms.form2.submit();
    }
  }
}

It may seem a little bit of overkill but it is generated automatically by our template engine and may be extended to more forms.

The body tag:

<body
 onLoad="init();
         window.formform1Changed=false;
         window.asked=false;
         window.doSaveForms=false;
         window.formform2Changed=false;"
 onbeforeunload="checkForChanges();">

And interesting part of one of the forms (the other one looks identically:

<input value="xyz" id="la" onchange="window.formform1Changed=true;" />
<input name="save" onclick="window.formform2Changed=false; window.formform1Changed=false;" type="submit" value="save" />

Now to the problem: If I change values in both forms and navigate away from the page, the question from the first form pops up. I click OK, the form is saved but the form1.submit() triggers a new onBeforeUnload event which breaks the whole logic of my idea.

The question now would be if there is a way to submit all forms on a page when only asking one time when the user navigates away?

Any help is highly appreciated!

Thanks.


Form submissions requires post-back, once you submit the first form, your page is redirected to the "action" of that form and you will lose the information in the rest of the forms you have.

Having multiple forms on the page is not the best idea, however, if you absolutely have to have them, the way to save all of them would be to replace full post-back with an AJAX call to a web-service (or a stand-alone page, that accepts query string parameters, though it's not as secure or flexible way). That way you can submit each form over the AJAX call without page redirecting.


As SLaks said, you will not be able to submit multiple forms in the way you are trying. You do have some other options though. Instead of traditional form submits you could make some kind of ajax calls to save the form data you care about. Here is an example using jquery and php (link)

0

精彩评论

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