简单实现了只要浏览器不关闭,session就不会失效的功能
1.javascript定时器定期ajax请求后台
2.避免用户因开多table导致频繁访问后台,利用cookie处理一下
function createXHR() { var xhr; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xhr=new XMLHttpRequest(); } else {// code for IE6, IE5 xhr=new ActiveXObject("Microsoft.XMLHTTP"); } return xhr; } function getCookie(cookieName) { if(document.cookie.length > 0) { var startIndex = document.cookie.indexOf(cookieName + '='); if(startIndex != -1) { //找到cookie了 startIndex = startIndex + cookieName.length + 1; var endIndex = document.cookie.indexOf(';', startIndex); if(endIndex = -1) { //当前cookie为最后一个,没有';' endIndex = document.cookie.length; } var cookieValue = escape(document.cookie.substring(startIndex, endIndex)); return cookieValue; } return null; } return null; }; var MINUTES = 10; //默认10分钟请求一次 function keepSession() { if(false) { //用户没有登录直接返回 return; } var LAST_REQUEST_TIME = 'last_equest_time'; var lastRequestTime = new Date().getTime(); var cookieValue = getCookie(LAST_REQUEST_TIME); if(!cookieValue) { //第一次登录,还没有cookie document.cookie = LAST_REQUEST_TIME + '=' + lastRequestTime; } else { var intervalTime = lastRequestTime - parseInt(cookieValue); if(intervalTime >= 1000*60*MINUTES) { //只要间隔大于等于规定时间才请求后台 var xhr = createXHR(); xhr.open('POST', 'url', true); xhr.send(null); // 更新cookie document.cookie = LAST_REQUEST_TIME + '=' + lastRequestTime; } } }; setInterval(keepSession, 1000*60*MINUTES);