【问题标题】:Call Ajax on unload if user clicks "OK"如果用户单击“确定”,则在卸载时调用 Ajax
【发布时间】:2010-11-15 20:57:06
【问题描述】:

我正在设计一个相当长的表单,它将每隔几分钟自动保存一次(即,使用 Ajax,表单数据将被插入或更新到 MySQL 数据库中)。但是,如果用户决定在提交表单之前退出页面,我想确保删除插入到数据库中的行。如果用户只是单击另一个链接或表单的取消按钮,这很容易做到。但我担心当用户:1)关闭页面,2)重新加载页面,或 3)点击浏览器的后退(或前进)按钮时会发生什么。我知道如何使用 unload 事件来创建一个确认对话框,要求用户确认他们想要离开页面。但是我不知道如果用户单击确定(“按确定继续”),如何进行 Ajax 调用(从数据库中删除该行)。如果用户在卸载事件期间单击确定按钮,有什么方法可以调用函数?

window.onbeforeunload = function() {
    if ($('#changes_made').val() == 'yes') //if user (partially) filled out the form
        {
            return "Are you sure?"
            if (/*user clicks OK */)  //What should the if statement evaluate here?
            {
                //make Ajax call
            }
        }
};

【问题讨论】:

    标签: javascript jquery mysql ajax


    【解决方案1】:
    $(document).ready(function() {   
        $(':input',document.myForm).bind("change", function() { 
           setConfirmUnload(true); 
        }); // Prevent accidental navigation away
    });
    
    function setConfirmUnload(on) {
         // To avoid IE7 and prior jQuery version issues   
         // we are directly using window.onbeforeunload event
         window.onbeforeunload = (on) ? unloadMessage : null;
    }
    
    function unloadMessage() {
    
        if(Confirm('You have entered new data on this page.  If you navigate away from this page without first saving your data, the changes will be lost.')) {
    
                $.ajax({
                   type: "POST",
                   url: "some.php",
                   data: "name=John&location=Boston",
                   success: function(msg){
                     alert( "Data Saved: " + msg );
                   }
                 });
    
        }
    
    }
    

    确保您已升级 jQuery 版本。 jQuery 1.3.2 版本有一个错误:

    Ticket #4418: beforeunload doenst work correctly

    或者使用原生函数:

    window.onbeforeunload = function() {....}
    

    【讨论】:

    • 这段代码似乎不起作用。当您单击“取消”按钮时,没有任何反应。无论哪种方式,该页面仍处于卸载状态。
    猜你喜欢
    • 2015-01-04
    • 1970-01-01
    • 2014-08-31
    • 2017-09-01
    • 2013-08-12
    • 2012-03-27
    • 1970-01-01
    • 2021-02-22
    • 1970-01-01
    相关资源
    最近更新 更多