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

在项目中,经常会遇到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; }

 

posted @ 2016-12-11 15:06  冰狼爱魔  阅读(1413)  评论(0编辑  收藏  举报