0

我已经使用 jquery、css 和 html 构建了一个网站。我使用 ajax 调用从服务器上的平面文件中检索数据并绘制图表。问题是有一个身份验证供应商应用程序,用户必须对其进行身份验证才能访问该站点。此供应商应用程序有 30 分钟的空闲超时,如果用户在 30 分钟内未执行任何操作,则会超时。

问题是,当它发生时,页面并没有按预期进入登录页面。

我想我需要一个服务器端调用来强制我的页面通过登录页面。

我创建了这个脚本做一个服务器调用来强制页面获取登录页面,但它似乎没有工作。

有什么想法可以解决这个问题吗?这是我的脚本:

<script>
$(document).ready(function(){
    function continueSession() {
        setTimeout(function(){
            $.get("somepage.php").always(continueSession);
        },30*1000);
    }
continueSession();
});
</script>

somepage.php 是服务器上的一个虚拟文件,它不做任何事情。有没有更好的方法来做到这一点?

4

1 回答 1

1

只需在发出 ajax 请求时检查响应代码。如果您收到错误,请将用户发送到登录页面。

$.get("somepage.php").always(function (response) {

  // check response code
  if (response.status !== 200) {

    // did not succeed. redirect to loging page
    window.location.replace("login_page.php");
    return;
  }

  // response is ok
});

您还可以使用location响应中的标头来确定重定向的位置。

$.get("somepage.php").always(function (response) {

    // check if it's a redirect (300 code)
    if (Math.round(response.status / 100.0) * 100 === 300) {

      // redirect to the location header
      window.location.href = response.getResponseHeader("location");
      return;
    }
});

你可以做这样的事情来检查间隔

var checkSession = function () {

  var isRedirect = function (code) {
    return Math.round(code / 100.0) * 100 === 300;
  };

  $.ajax({
    type  : "HEAD", // https://ochronus.com/http-head-request-good-uses/
    async : true,
    url   : "somepage.php",
    success: function (_, _, response) {
      if (isRedirect(response.code)) {
        window.location.href = response.getResponseHeader("location");
      }
    }
  });
};

$(function () {
  // check the session every 30 seconds
  setInterval(checkSession, 30*1000);
});
于 2014-01-28T16:10:15.817 回答