如何处理AJAX请求中的会话超时

时间:2022-10-19 22:23:40

I'm sure you're all familiar with the voting systems that use AJAX (Um... look right over there <----)

我相信你们都熟悉使用AJAX的投票系统(嗯......看那边<----)

I have something similar and when you vote up or down it uses AJAX to request the new value from votes.php. The problem is that I am using a session to get the userid so a person can only vote once. What happens if they sit on the page for an hour and then vote so the session is no longer there? What would be a good way of handling this situation? Should I redirect their page to the login screen? If so, how can I do that from the votes.php page that is being referenced by the AJAX request? Am I overlooking a good way of handling this situation? Any advice would be helpful.

我有类似的东西,当你向上或向下投票时,它使用AJAX从votes.php请求新值。问题是我正在使用会话来获取用户ID,因此一个人只能投票一次。如果他们在页面上坐了一个小时然后投票那么会话不再存在会发生什么?处理这种情况的好方法是什么?我应该将他们的页面重定向到登录屏幕吗?如果是这样,我怎么能从AJAX请求引用的votes.php页面中做到这一点?我是否忽略了处理这种情况的好方法?任何意见将是有益的。

6 个解决方案

#1


11  

Consider returning an http status of 401, and a JSON object detailing the reason. If you're using jQuery, that'll drop you to the error() callback, which you can then parse your object.

考虑返回401的http状态,以及详细说明原因的JSON对象。如果您正在使用jQuery,那么您将转到error()回调,然后您可以解析您的对象。

$.ajax({
  data: {},
  dataType: 'html',
  success: function(data) {
    // do whatever here
  },
  type: 'POST',
  url: 'myserver.com',
  error: function(XMLHttpRequest, textStatus, errorThrown) {
    // XMLHttpRequest.responseText has your json string
    // XMLHttpRequest.status has the 401 status code
    if (XMLHttpRequest.status === 401) {
      location.href = 'login.php';
    }
  }
});

I'm not familiar with PHP anymore, but this should work for just about any environment. You may have to suppress any automatic login form redirection though. In asp.net mvc the framework will see the 401 and push the default login form back, with a status of 200.

我不再熟悉PHP,但这应该适用于任何环境。您可能必须禁止任何自动登录表单重定向。在asp.net mvc中,框架将看到401并返回默认登录表单,状态为200。

#2


1  

You should only store a link to the users identity in the session. Use sessions to identify a user as x and then get user x's information from the database.

您应该只在会话中存储指向用户身份的链接。使用会话将用户标识为x,然后从数据库中获取用户x的信息。

If your problem is with users sessions timing out then you should reconsider how you're using your sessions. Perhaps make them last until the browser closes? If you really want to make them a duration, then perhaps ping the server in intervals to keep the session alive.

如果您的问题是用户会话超时,那么您应该重新考虑如何使用会话。也许让它们持续到浏览器关闭?如果你真的想让它们成为一个持续时间,那么可能会间隔地ping服务器以保持会话的活跃性。

Decide in your php script whether or not the user should be able to vote. If the session isn't set, or if they have already voted, return a message that you can identify with on the client side. If they already voted perhaps return "voted":"true" in a JSON object. Use JS to parse this object and understand what it means, taking the appropriate action. If the session isn't set, perhaps return "session_set":"false", and then make javascript redirect with a window.location = "login.php" etc.

确定您的PHP脚本是否应该能够投票。如果未设置会话,或者他们已经投票,则返回您可以在客户端识别的消息。如果他们已经投票,或许在JSON对象中返回“voteed”:“true”。使用JS解析此对象并理解其含义,采取适当的操作。如果未设置会话,可能返回“session_set”:“false”,然后使用window.location =“login.php”等进行javascript重定向。

Only increment the counter for the user on a successful return of a counted vote.

只有在成功返回计票时才为用户增加计数器。

#3


1  

This is an old thread, but I wanted to share my solution that is working really well.

这是一个老线程,但我想分享我的解决方案,该方法非常有效。

In my framework the system redirects the user to the login form any time they try to access a page and the session has timed out or is not valid. I added to the top of the login form the following html comment:

在我的框架中,系统会在用户尝试访问页面时将用户重定向到登录表单,并且会话已超时或无效。我在登录表单的顶部添加了以下html注释:

<!--LOGINFORM-->

I created a wrapper for jQuery's $.ajax function which checks for this string on every request, and if it is there it shows a dialog popup saying that their session has timed out.

我为jQuery的$ .ajax函数创建了一个包装器,它在每个请求上检查这个字符串,如果它在那里,它会显示一个对话框弹出窗口,说明它们的会话超时了。

You can use this by just calling:

你可以通过调用来使用它:

ajax.get('http://someurl.com', function(data){
    //Do stuff
});

Hope it helps someone.

希望它可以帮到某人。

var ajax = {
    check_login : function(resp){
        if (resp.substring(0, 16) === "<!--LOGINFORM-->"){
            // Show a popup or redirect them to login page!
            return true;
        }
        return false;
    },
    get : function(url, success){       
        if (typeof data =='undefined'){
            data = null;
        }

        $.ajax({
            url: url,
            type : 'GET',
            success : function(resp){
                if (!ajax.check_login(resp)) {
                    success(resp);
                }
            },
        });
    }   
};

#4


0  

You structure the Javascript code that makes the Ajax request to accept a special result (say, -1 where a >=0 number would normally be, such as, a count of votes) to mean "sorry bub, you're timed out" and redirect to the re-login page (which can take as an optional parameter a message explaining to the user they timed out, &c).

您构造了使Ajax请求接受特殊结果的Javascript代码(例如,-1,其中> = 0数字通常是,例如,投票数),表示“对不起,你已经超时”并重定向到重新登录页面(可以作为可选参数,向用户说明他们超时的消息,&c)。

#5


0  

You could create a javascript function that could ping the server every 10 minutes via something like

您可以创建一个javascript函数,可以通过类似的方式每10分钟ping一次服务器

setTimeout("Ping()", 60000); 

If you want to navigate the user to the login page if they connect with a faulty session then I would first verify the session and if it fails send a

如果您想要将用户导航到登录页面,如果他们连接有错误的会话,那么我将首先验证会话,如果失败则发送

header("Location: ...");

http://ca2.php.net/manual/en/function.header.php

#6


0  

From a user perspective, the best solution is to pop up a message and login form, saying something like "You are not logged in or your session timed out". Digg does this very well.

从用户的角度来看,最好的解决方案是弹出一条消息和登录表单,说“你没有登录或你的会话超时”。 Digg做得非常好。

As for the actual AJAX implementation, swilliams' 401 suggestion is solid. Alternatively, you can simply return a specific string on failure.

至于实际的AJAX实现,swilliams的401建议是可靠的。或者,您可以在失败时返回特定字符串。

#1


11  

Consider returning an http status of 401, and a JSON object detailing the reason. If you're using jQuery, that'll drop you to the error() callback, which you can then parse your object.

考虑返回401的http状态,以及详细说明原因的JSON对象。如果您正在使用jQuery,那么您将转到error()回调,然后您可以解析您的对象。

$.ajax({
  data: {},
  dataType: 'html',
  success: function(data) {
    // do whatever here
  },
  type: 'POST',
  url: 'myserver.com',
  error: function(XMLHttpRequest, textStatus, errorThrown) {
    // XMLHttpRequest.responseText has your json string
    // XMLHttpRequest.status has the 401 status code
    if (XMLHttpRequest.status === 401) {
      location.href = 'login.php';
    }
  }
});

I'm not familiar with PHP anymore, but this should work for just about any environment. You may have to suppress any automatic login form redirection though. In asp.net mvc the framework will see the 401 and push the default login form back, with a status of 200.

我不再熟悉PHP,但这应该适用于任何环境。您可能必须禁止任何自动登录表单重定向。在asp.net mvc中,框架将看到401并返回默认登录表单,状态为200。

#2


1  

You should only store a link to the users identity in the session. Use sessions to identify a user as x and then get user x's information from the database.

您应该只在会话中存储指向用户身份的链接。使用会话将用户标识为x,然后从数据库中获取用户x的信息。

If your problem is with users sessions timing out then you should reconsider how you're using your sessions. Perhaps make them last until the browser closes? If you really want to make them a duration, then perhaps ping the server in intervals to keep the session alive.

如果您的问题是用户会话超时,那么您应该重新考虑如何使用会话。也许让它们持续到浏览器关闭?如果你真的想让它们成为一个持续时间,那么可能会间隔地ping服务器以保持会话的活跃性。

Decide in your php script whether or not the user should be able to vote. If the session isn't set, or if they have already voted, return a message that you can identify with on the client side. If they already voted perhaps return "voted":"true" in a JSON object. Use JS to parse this object and understand what it means, taking the appropriate action. If the session isn't set, perhaps return "session_set":"false", and then make javascript redirect with a window.location = "login.php" etc.

确定您的PHP脚本是否应该能够投票。如果未设置会话,或者他们已经投票,则返回您可以在客户端识别的消息。如果他们已经投票,或许在JSON对象中返回“voteed”:“true”。使用JS解析此对象并理解其含义,采取适当的操作。如果未设置会话,可能返回“session_set”:“false”,然后使用window.location =“login.php”等进行javascript重定向。

Only increment the counter for the user on a successful return of a counted vote.

只有在成功返回计票时才为用户增加计数器。

#3


1  

This is an old thread, but I wanted to share my solution that is working really well.

这是一个老线程,但我想分享我的解决方案,该方法非常有效。

In my framework the system redirects the user to the login form any time they try to access a page and the session has timed out or is not valid. I added to the top of the login form the following html comment:

在我的框架中,系统会在用户尝试访问页面时将用户重定向到登录表单,并且会话已超时或无效。我在登录表单的顶部添加了以下html注释:

<!--LOGINFORM-->

I created a wrapper for jQuery's $.ajax function which checks for this string on every request, and if it is there it shows a dialog popup saying that their session has timed out.

我为jQuery的$ .ajax函数创建了一个包装器,它在每个请求上检查这个字符串,如果它在那里,它会显示一个对话框弹出窗口,说明它们的会话超时了。

You can use this by just calling:

你可以通过调用来使用它:

ajax.get('http://someurl.com', function(data){
    //Do stuff
});

Hope it helps someone.

希望它可以帮到某人。

var ajax = {
    check_login : function(resp){
        if (resp.substring(0, 16) === "<!--LOGINFORM-->"){
            // Show a popup or redirect them to login page!
            return true;
        }
        return false;
    },
    get : function(url, success){       
        if (typeof data =='undefined'){
            data = null;
        }

        $.ajax({
            url: url,
            type : 'GET',
            success : function(resp){
                if (!ajax.check_login(resp)) {
                    success(resp);
                }
            },
        });
    }   
};

#4


0  

You structure the Javascript code that makes the Ajax request to accept a special result (say, -1 where a >=0 number would normally be, such as, a count of votes) to mean "sorry bub, you're timed out" and redirect to the re-login page (which can take as an optional parameter a message explaining to the user they timed out, &c).

您构造了使Ajax请求接受特殊结果的Javascript代码(例如,-1,其中> = 0数字通常是,例如,投票数),表示“对不起,你已经超时”并重定向到重新登录页面(可以作为可选参数,向用户说明他们超时的消息,&c)。

#5


0  

You could create a javascript function that could ping the server every 10 minutes via something like

您可以创建一个javascript函数,可以通过类似的方式每10分钟ping一次服务器

setTimeout("Ping()", 60000); 

If you want to navigate the user to the login page if they connect with a faulty session then I would first verify the session and if it fails send a

如果您想要将用户导航到登录页面,如果他们连接有错误的会话,那么我将首先验证会话,如果失败则发送

header("Location: ...");

http://ca2.php.net/manual/en/function.header.php

#6


0  

From a user perspective, the best solution is to pop up a message and login form, saying something like "You are not logged in or your session timed out". Digg does this very well.

从用户的角度来看,最好的解决方案是弹出一条消息和登录表单,说“你没有登录或你的会话超时”。 Digg做得非常好。

As for the actual AJAX implementation, swilliams' 401 suggestion is solid. Alternatively, you can simply return a specific string on failure.

至于实际的AJAX实现,swilliams的401建议是可靠的。或者,您可以在失败时返回特定字符串。