2009-02-16 121 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