简体   繁体   English

Javascript onunload 表单提交未提交数据

[英]Javascript onunload form submit isn't submitting data

I currently have form that checks if a user has unsubmitted changes when they leave the page with a function called through the onunload event.我目前有一个表单,用于检查用户在离开页面时是否有未提交的更改,并使用通过onunload事件调用的函数。 Here's the function:这是函数:

function saveOnExit() {
    var answer = confirm("You are about to leave the page. All unsaved work will be lost. Would you like to save now?");
    if (answer) {
       document.main_form.submit();
    }
}

And here's the form:这是表格:

<body onunload="saveOnExit()">
<form name="main_form" id="main_form" method="post" action="submit.php" onsubmit="saveScroll()">
    <textarea name="comments"></textarea>
    <input type="submit" name="submit2" value="Submit!"/>
</form>

I'm not sure what I'm doing wrong here.我不确定我在这里做错了什么。 The data gets submitted and saved in my database if I just press the submit button for the form.如果我只需按下表单的提交按钮,数据就会被提交并保存在我的数据库中。 However, trying to submit the form through the onunload event doesn't result in anything being stored, from what I can tell.但是,据我所知,尝试通过onunload事件提交表单不会导致存储任何内容。 I've tried adding onclick alerts to the submit button and onsubmit alerts to the form elements and I can verify that the submit button is being triggered and that the form does get submitted.我已经尝试向提交按钮添加onclick警报,向表单元素添加onsubmit警报,我可以验证提交按钮是否被触发并且表单确实被提交。 However, nothing gets passed stored in the database.但是,没有任何内容通过存储在数据库中。 Any ideas as to what I'm doing wrong?关于我做错了什么的任何想法?

Try onbeforunload 卸载前试试

An event that fires before the unload event when the page is unloaded.卸载页面时在 unload 事件之前触发的事件。

Also give return false at the end of the function for the condition in which the data should not be submitted.对于不应提交数据的条件,还要在函数结束时return false

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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