【问题标题】:Confirm dialog onbeforeunload卸载前确认对话框
【发布时间】:2017-11-27 02:01:15
【问题描述】:

您好,我已经阅读了很多关于该主题的其他帖子,但仍然感到困惑。我只想在我的页面被卸载之前实现两件简单的事情。

  1. 如果有任何未保存的数据,请保存。询问是/否以保存它(使用确认())
  2. 保存页面上的当前选择

我是这样做的。

window.onbeforeunload = function (e) {


    var model = _selectedClassNodes + ";" + _selectedIndicatorNodes + ";" + _selectedNode + ";" + _pageHeaderId;

    $.ajax({
        url: "@Url.Action("SaveDefaultSettings", "Maps")",
        type: 'get',
        data: { defaultSettings: model },
        success: function (data) {


        }
    });

    //if some unsaved data exists
    if (editedRows.length > 0) {

        if (confirm("Do you wish to save changes before continuing? CLick 'OK' for 'Yes' and 'Cancel' for 'No'")) {
            SaveGridData();
        }
    }


};

SaveDefaultSettings 总是被触发,因为我使用断点进行了调试,但没有出现确认框。

据我所知,confirm() 之前工作正常,但今天我注意到它已停止工作。我正在使用 chrome v 62.0

如果我将代码更改为

 window.onbeforeunload = function (e) {

    return "Do you wish to save changes before continuing? CLick 'OK' for 'Yes' and 'Cancel' for 'No'";

    var model = _selectedClassNodes + ";" + _selectedIndicatorNodes + ";" + _selectedNode + ";" + _pageHeaderId;

    $.ajax({
        url: "@Url.Action("SaveDefaultSettings", "Maps")",
        type: 'get',
        data: { defaultSettings: model },
        success: function (data) {



        }
    });
 };

现在默认对话框显示“您所做的更改可能不会保存”重新加载/不重新加载

【问题讨论】:

  • 您不能在 beforeunload 中使用任何阻塞代码,例如警报或确认。多年来,它被滥用了很多浏览器供应商不得不限制它的功能......甚至在大多数浏览器中不显示自定义消息的程度

标签: javascript ajax asp.net-mvc-4 confirm


【解决方案1】:

来自MDN Web docs

如果将字符串分配给 returnValue 事件属性,则会出现一个对话框 出现要求用户确认离开页面(请参阅 下面的例子)。一些浏览器将返回的字符串显示在 对话框,但其他人显示自己的消息。

这就是为什么我看到的是不同的消息,而不是我返回的消息。

我之前提到它工作的那一点令人困惑,因为在另一个按钮单击时也使用了相同的确认对话框消息。

我的最终代码是

window.onbeforeunload = function (e) {


    var model = _selectedClassNodes + ";" + _selectedIndicatorNodes + ";" + _selectedNode + ";" + _pageHeaderId;

    $.ajax({
        url: "@Url.Action("SaveDefaultSettings", "Maps")",
        type: 'get',
        data: { defaultSettings: model },
        success: function (data) {



        }
    });

    //if some unsaved data exists
    if (editedRows.length > 0) {
        return "There are some changes in grid data. You need to click 'Save Changes' or 'Cancel Changes' button on grid before continuing.";
    }


};

【讨论】:

    猜你喜欢
    • 2018-12-29
    • 2011-06-06
    • 1970-01-01
    • 1970-01-01
    • 2019-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-07
    相关资源
    最近更新 更多