解决ajax 遇到session失效后自动跳转的问题

时间:2024-08-17 11:36:20

在项目中,经常会遇到session失效后,点击任何链接无反应的情况!这样给客户的体验就不是很好,以为是系统出了故障!所以在项目中我们会处理session失效后的跳转问题(一般给用户提示,并跳转后登录页面),代码实现如下所示:

// 着重处理ajax请求跳转的问题,因为form表单请求可以直接在服务器端完成跳转
$.ajaxSetup({
  contentType:"application/x-www-form-urlencoded;charset=utf-8",
  cache:false,
global: true,
complete: function (XMLHttpRequest, textStatus) {
var data = XMLHttpRequest.responseText;
if(data.substr(0,15) == "session-invalid") {
alert('当前会话已失效,请重新登陆!');
if( window.top != window.self ){
window.top.location = "/index.php?r=site/logout"; // 跳转到登录页面
}else{
window.location = "/index.php?r=site/logout";
}
}
}
});
// PHP服务端代码处理
if($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' && !$_SESSION['sUserId']){
//如果是ajax 请求
echo 'session-invalid';
exit;
}