如何在没有JQuery的情况下,通过对服务器的基本ajax调用,根据浏览器上的用户活动保持服务器会话活动

How to keep server session active based on user activity on the browser with basic ajax call to server without JQuery

本文关键字:活动 服务器 浏览器 调用 用户 会话 ajax 情况下 JQuery      更新时间:2023-09-26

在我的站点中,服务器会话超时为30分钟。

<system.web>
      <sessionState timeout="30" />
 </system.web>

但是,如果用户通过键入长注释或选择几个复选框在浏览器上处于活动状态,我需要在不注销的情况下保持用户的活动状态。当用户在打字10分钟后变得不活跃、离开20分钟后再次打字时,用户不应该被注销,因为空闲时间只是20而不是30分钟,但如果用户离开了整整30分钟,则用户应该被注销。我找到了下面的代码来检查用户活动。如果我在web.config中没有上面提到的行,代码就会工作,我认为这是错误的。如果用户在浏览器上处于活动状态,我希望保持这一点,并防止超时发生。此外,我不想简单地将用户重定向到logout.aspx。我想结束服务器会话。有没有一个解决方案,而不必创建伪aspx页面,或者必须保留一个空页面才能避免404?有什么解决方案可以在不使用Jquery的情况下对服务器进行基本的Ajax调用?谢谢

var IDLE_TIMEOUT = 60; //seconds
var _idleSecondsCounter = 0;
document.onclick = function() {
    _idleSecondsCounter = 0;
};
document.onmousemove = function() {
    _idleSecondsCounter = 0;
};
document.onkeypress = function() {
    _idleSecondsCounter = 0;
};
window.setInterval(CheckIdleTime, 1000);
function CheckIdleTime() {
    _idleSecondsCounter++;
       if (_idleSecondsCounter >= IDLE_TIMEOUT) {
        alert("Time expired!");
        document.location.href = "logout.aspx";
    }
}

我认为您可以使用http选项方法。

function keepOnline(url) {
  var xhr ;
  if (window.XMLHttpRequest) {
    xhr=new XMLHttpRequest();
  }
  else if (window.ActiveXObject) {
    xhr=new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.open("OPTION",url,true);
  xmlhttp.send(null);
}