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>

したがって、検出はウィンドウ メソッドではなく、リンクのクリック メソッドとフォーム送信で行われます。

/* 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 に答える