3

在 window.onbeforeunload 事件中,有没有办法检测新请求是 POST(在同一页面上)还是 GET(转到页面)?看到新的 document.location 也很棒。

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?";
    }
}
4

2 回答 2

13

这就是我刚刚做到的:

$(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.';
  }
});
于 2009-07-23T19:26:42.623 回答
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 方法中,而是发生在你的链接的 click 方法和表单提交中。

/* 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);
});
于 2009-02-16T06:54:59.297 回答