Submit form before user leaves page in javascript/jquery

喜夏-厌秋 提交于 2019-12-11 10:06:22

问题


Is it possible to create a more customized leaving-page event? Right now I am using the window.onbeforeunload event to warn users of their unsaved changes before leaving the page.

What I really want to do though, is to give the user the option to save their data right away before leaving the page(possibly with a button in a pop up) and then continue redirecting them. I assume it's not possible to let onbeforeunload do some extra work before displaying the message(I tried).

So is what I want even possible or a good idea?


回答1:


The model used by most large sites (including stack) is simply to warn users that they have unsaved data. I suggest you replicate that behaviour.




回答2:


You're not the first one that wants to handle a user leaving the page gracefully.

Unfortunately onBeforeUnload is what you have available and that's what you have to work with.

The reason that it is only possible to show a message is that otherwise evil sites might try to cancel the navigation to prevent the user from leaving the page.




回答3:


If u use PHP, u can do it with onbeforeunload and ajax, like

<html>
<head>
<script type="text/javascript">
function close_logout() {
 var xmlhttp=new XMLHttpRequest();
 xmlhttp.open("GET", "logout_script.php", true);
 xmlhttp.send();
}
</script>
</head>
<body onbeforeunload="close_logout()">
U'r page and stuff
</body>
</html>

Then u can have some PHP function and so on in the php site.



来源:https://stackoverflow.com/questions/21039815/submit-form-before-user-leaves-page-in-javascript-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!