2010-11-15 68 views
0

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

回答

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有一个bug:

Ticket #4418: beforeunload doenst work correctly

或使用本机的功能:此代码似乎

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

并不毕竟工作。当你点击“取消”按钮时,没有任何反应。该页面仍然以任何方式卸载。 – jake 2010-11-15 21:58:15

相关问题