Как бороться с тайм-аутами сеанса в AJAX-запросах

Я считаю, что это самое чистое решение без использования каких-либо мутаций или незнакомых классов.

<?php

function flatten($array)
{
    return array_reduce($array, function($acc, $item){
        return array_merge($acc, is_array($item) ? flatten($item) : [$item]);
    }, []);
}


// usage
$array = [1, 2, [3, 4], [5, [6, 7]], 8, 9, 10];
print_r(flatten($array));
14
задан Joe Phillips 17 June 2009 в 04:41
поделиться

5 ответов

Рассмотрите возможность возврата статуса http 401 и объекта 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';
    }
  }
});

Я больше не знаком с PHP, но это должно работать для практически в любой среде. Однако вам может потребоваться подавить любое автоматическое перенаправление формы входа. В asp.net mvc фреймворк увидит 401 и вернет форму входа по умолчанию со статусом 200.

11
ответ дан 1 December 2019 в 14:33
поделиться

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.

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.

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.

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

1
ответ дан 1 December 2019 в 14:33
поделиться

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).

0
ответ дан 1 December 2019 в 14:33
поделиться

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

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

0
ответ дан 1 December 2019 в 14:33
поделиться

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.

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

0
ответ дан 1 December 2019 в 14:33
поделиться
Другие вопросы по тегам:

Похожие вопросы: