确认对话框onbeforeunload

时间:2017-11-27 02:01:16

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

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

  1. 如果有任何未保存的数据保存。请求是/否保存(使用confirm())
  2. 保存页面上的当前选择
  3. 我这样做。

    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 总是被触发,因为我已经使用断点调试但没有出现确认框。

    据我所知,确认()之前工作正常,但今天我注意到它已经停止工作了。我使用的是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) {
    
    
    
            }
        });
     };
    

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

1 个答案:

答案 0 :(得分:0)

来自Link

  

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

这就是为什么我会看到不同的信息,而不是我要回复的信息。

我之前提到它的工作原理是混乱,因为在另一个按钮点击时也使用了相同的确认对话框消息。

我的最终代码是

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.";
    }


};