捕获window.onbeforeunload的结果 [英] capture the result of window.onbeforeunload

查看:233
本文介绍了捕获window.onbeforeunload的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个场景,当用户在window.onbeforeunload上单击是时我必须保存更改,因为我需要提交表单,选择否时不会发生任何事情。

I have a scenario, I have to save the changes when user clicks yes on window.onbeforeunload for that I need to submit the form and nothing should be happen when selected no.

非常感谢任何帮助

我试过这个

window.onbeforeunload= function(){
    var r = confirm("Are you sure you want to leave this page?");
    if (r == true) {
        readForm.action = '/SREPS/read.do' ;
        readForm.submit();
    }else{
        return false;
    }
}

当我们点击取消时它没有100%工作在window.confirm期间出现另一个对话框,说明来自网页的消息错误要求确认离开此页面并留在此页面上。在这种情况下,如果用户选择离开此页面。我无法提交表格。

It did not worked 100% when ever we hit Cancel during window.confirm another dialog appears saying that message from webpage false asking for confirmation leave this page and stay on this page. In this case if the user selects leave this page. I am not able to submit the form.

推荐答案

无法在<$中使用您自己的对话框C $ C> onbeforeunload 。你唯一能做的就是返回一个要显示的字符串(在某些浏览器上)。您无法阻止浏览器离开,只有用户可以控制它。

You cannot use your own dialog in onbeforeunload. The only thing you can do is return a string to be displayed (on some browsers). You cannot stop the browser from leaving, only the user can control that.

您可以执行的操作如下:

What you can do is the following:

window.onbeforeunload = function(){
    return 'Are you sure you want to leave this page?';
};

这将询问用户是否要离开。然后你可以使用 onunload 事件在他们离开时运行一个函数。从那里,你可以提出一个同步的AJAX请求来提交表格。

This will ask the user if they want to leave or not. Then you can use the onunload event to run a function when they leave. From there, you can make a "synchronous" AJAX request to submit the form.

window.onunload = function(){
    var request = new XMLHttpRequest();
    request.open('POST', '/SREPS/read.do', false);
    request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

    request.send(new FormData(readForm));
};

如果你使用的是jQuery,你可以这样做:

If you are using jQuery, you can do:

window.onunload = function(){
    $.ajax({
        url: '/SREPS/read.do',
        type: 'post',
        async: false,
        data: $(readForm).serialize()
    });
};

这篇关于捕获window.onbeforeunload的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆