2009-02-16 49 views
3

在window.onbeforeunload事件中,有一種方法可以檢測新請求是POST(在同一頁面上)還是GET(進入頁面)?看到新的document.location也很棒。window.onbeforeunload檢測POST或GET

window.onbeforeunload = winClose; 
function winClose() { 
    //Need a way to detect if it is a POST or GET 
    if (needToConfirm) {  
     return "You have made changes. Are you sure you want?"; 
    } 
} 

回答

0

聽起來像你需要附加到窗體或特定鏈接的東西。如果事件是由鏈接引發的,並且有一個請求字符串充滿變量,則它將充當GET。如果是表單,則必須檢查METHOD,然後根據表單本身提交的數據來確定URL。

<a href="thisPage.php">No method</a> 
<a href="thisPage.php?usrName=jonathan">GET method</a> 
<form method="GET" action="thisPage.php"> 
    <!-- This is a GET, according to the method --> 
    <input type="text" name="usrName" value="jonathan" /> 
</form> 
<form method="POST" action="thisPage.php"> 
    <!-- This is a POST, according to the method --> 
    <input type="text" name="usrName" value="jonathan" /> 
</form> 

因此,檢測不會發生在window方法中,而是發生在您的鏈接的點擊方法和表單提交中。

/* Check method of form */ 
$("form").submit(function(){ 
    var method = $(this).attr("method"); 
    alert(method); 
}); 

/* Check method of links...UNTESTED */ 
$("a.checkMethod").click(function(){ 
    var isGet = $(this).attr("href").get(0).indexOf("?"); 
    alert(isGet); 
}); 
+0

是的,我想知道我是如何從檢查的JavaScript方法? 例如這樣的東西..例如window.Method ==「POST」 – rid00z 2009-02-16 23:21:32

12

這是怎麼了我只是做了它:

$(document).ready(function(){ 
    var action_is_post = false; 
    $("form").submit(function() { 
    action_is_post = true; 
    }); 

    window.onbeforeunload = confirmExit; 
    function confirmExit() 
    { 
    if (!action_is_post) 
     return 'You are trying to leave this page without saving the data back to the server.'; 
    } 
}); 
+0

謝謝,這正是我正在尋找! – Annagram 2009-08-25 22:35:08