2010-11-15 26 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

相關問題