3

There are lots of similar questions on here, but I haven't found any that deal with stopping a user from leaving a page after submitting a form (i.e. while it's processing).

I have a page on my website with a form that takes a long time to submit (sometimes as long as 15 seconds), so I want to have a popup warning to keep the user on the page after they submit the form.

The problem is that no matter how I try using window.onbeforeunload, I always get a confirmation dialog from that function when the form is submitted, which is not what I want. I don't want the user to get the confirmation dialog when the form is submitted, but rather after it's submitted and only if they try to leave the page after that.

HTML:

<form id="myform" method="post" action="" onsubmit="formSubmitted();">
    <button type="submit" onclick="return checkForm();">submit form</button>
</form>

Javascript:

formSubmittedFlag = 0;

function checkForm()
{
    ...

    if(...)
    {
        return true;
    }
    else
    {
        return false;
    }
}


function formSubmitted()
{
    formSubmittedFlag = 1;
}



window.onbeforeunload = function()
{
    if(formSubmittedFlag == 1)
    {
        return "Are you sure you want to leave the page?";
    }
}

Is there a way to accomplish what I'm wanting?

4

2 回答 2

2

Submit the form using AJAX rather than the form's built-in action. The jQuery Form Plugin may be helpful.

于 2013-02-28T00:52:17.713 回答
1

replace the contents of formSubmitted with this:

sessionStorage.formSubmittedFlag=true;
notReloaded=true;

And replace the contents of window.onbeforeunload with this:

    if(sessionStorage.formSubmittedFlag===true&&notReloaded!=true)
        return 'do you want to leave?';
于 2013-02-28T00:57:11.310 回答