use*_*640 5 javascript ajax jquery redirect onbeforeunload
I have been trying to bind beforeunload event by calling the following script so that I can go to the specified URL through AJAX. The problem is that the AJAX is not working the first time as the URL does not get called when the first time I do the page refresh. The second time ajax works. This problem gets fixed when I set async to false but then the alert popup inside success doesn't show up. I need alert box to also show up in success block.
<script type="text/javascript">
$( document ).ready(function() {
// this method will be invoked when user leaves the page, via F5/refresh, Back button, Window close
$(window).bind('beforeunload', function(event){
// invoke the servlet, to logout the user
$.ajax({
cache: false,
type: "GET",
url: "LogoutController" ,
success: function (data) {
alert("You have been logged out");
}
});
});
});
</script>
Run Code Online (Sandbox Code Playgroud)
beforeunload将等待事件处理程序完成其执行后再关闭页面。由于 ajax 调用是异步的,beforeunload因此不会等待它完成(但是您的服务器仍然应该收到请求)。这是预期的行为,我不认为这是解决这个问题的方法。
可以使用以下代码重现此行为:
window.onbeforeunload = function () {
console.log("bye");
setTimeout(function () {
console.log("bye1");
}, 200);
console.log("bye2")
};
//bye
//bye2
Run Code Online (Sandbox Code Playgroud)
另外,您应该注意,根据MDN规范,alert() 可以被忽略:
自 2011 年 5 月 25 日起,HTML5 规范规定在此事件期间对 window.alert()、window.confirm() 和 window.prompt() 方法的调用可能会被忽略。
当这种情况发生在 chrome 上时(我仅检查过的浏览器),您将在控制台中收到以下消息:
Blocked alert('test') during beforeunload.
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1870 次 |
| 最近记录: |