javascript window.onbeforeunload检测是否为POST或GET

hpcdzsge  于 2023-01-04  发布在  Java
关注(0)|答案(2)|浏览(107)

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

ygya80vv1#

我刚才是这么做的:

$(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.';
  }
});
0sgqnhkj

0sgqnhkj2#

听起来像是你需要附加到表单或特定链接上的东西。如果事件是由链接引发的,并且有一个充满变量的请求字符串,它将充当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);
});

相关问题