问题的原因是执行 AJAX 调用时会话 cookie 轮换,CodeIgniter 3 中包含了正确的修复
您有四个选择:
Cope:
我之前自己也遇到过这个问题,但并不知道它的确切原因。总之,我保存了每个 XMLHttpRequest 的 promise,如果遇到 HTTP 状态码 401,客户端应用程序会以弹窗的形式请求凭证,然后重试 AJAX promise。
使用 jQuery 的客户端,只需添加这个 ajaxError 处理程序:
$(document).ajaxError(function (e, xhr, settings, exception) {
if (xhr.status == 401)
{
// open your popup
$('#login-popup').modal('open');
// attach the xhr object to the listener
$(document).bind( "retry-xhr", {
xhro: xhr
},
function( event ) {
// retry the xhr when fired
$.ajax( event.data.xhro );
});
}
});
当您重新登录时,只需调用它来重试您的请求:
$(document).trigger('retry-xhr');
服务器端,你只需要在你的构造函数中添加一个 if
if (!$this->session->userdata('logged_in') && $this->input->is_ajax_request())
{
$this->output->set_status_header('401');
exit;
}
这很有用,因为有些用户会在一夜之间打开他们的 Web 应用程序窗口,并且会话超时会启动。然后用户会打电话给我说无法执行任何 AJAX 功能,我不得不告诉他们按 F5
附言。如果在 Angular 上,我已经成功使用了 HTTP Auth Interceptor Module
哈克:
见这篇文章,他的解决方案是在 ci_session 表中创建另一个字段并检查两个 cookie,因此您的会话在轮换后仍然有效。
它还详细解释了导致此故障的原因
http://www.hiretheworld.com/blog/tech-blog/codeigniter-session-race-conditions
升级:
开始使用已经修复的下一个版本:
https://github.com/EllisLab/CodeIgniter/tree/release/3.0
补丁
替换 system/libraries/Session.php 中的第 346 行(函数 sess_update())
if (($this->userdata['last_activity'] + $this->sess_time_to_update) >= $this->now)
和:
if (($this->userdata['last_activity'] + $this->sess_time_to_update) >= $this->now || $this->CI->input->is_ajax_request())