Ajax应该在window.beforeunload事件上单击离开按钮后执行

时间:2018-09-11 07:46:36

标签: javascript jquery ajax javascript-events

问题在于,当我刷新浏览器时,默认弹出窗口会显示带有“离开”和“停留”按钮。它同时在停留和离开按钮上执行AJAX代码。

当我只想离开页面时,我只想执行它,以便在单击离开时注销用户。

window.top.onbeforeunload = function() {
  clearSession;
  return 'Done';
}

function clearSession() {
  var xmlHttp;
  try {
    xmlHttp = new XMLHttpRequest();
  } catch (e) {
    try {
      xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
      try {
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (e) {
        alert("Your browser does not support AJAX!");
        return false;
      }
    }
  }
  // xmlHttp.onreadystatechange=handleOnReadyStateChange;

  xmlHttp.open("POST", "/navigate.html?action=logout", false);

  xmlHttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

  xmlHttp.send();
  setTimeout(function() {
    window.top.location.href = '/Login.html';
  }, 1000);
}

0 个答案:

没有答案