AJAX(Asynchronous JavaScript and XML)是一种在不重新加载整个页面的情况下与服务器交换数据并更新部分网页的技术。会话超时是指用户在一段时间内没有与服务器交互后,服务器端会话(Session)失效的情况。
服务器检测到会话过期时,返回特定的HTTP状态码(如401未授权):
// 前端统一处理
$.ajax({
url: '/api/data',
success: function(data) {
// 正常处理
},
error: function(xhr) {
if(xhr.status == 401) {
window.location.href = '/login?timeout=1';
}
}
});
// 使用axios拦截器示例
axios.interceptors.response.use(
response => response,
error => {
if (error.response.status === 401) {
window.location.href = '/login';
}
return Promise.reject(error);
}
);
定期发送请求保持会话活跃:
setInterval(function() {
$.get('/keepalive');
}, 5 * 60 * 1000); // 每5分钟发送一次
let lastActivity = new Date();
document.addEventListener('mousemove', () => {
lastActivity = new Date();
});
setInterval(() => {
const now = new Date();
if ((now - lastActivity) / (1000 * 60) > 15) { // 15分钟无活动
// 显示会话即将过期警告
}
}, 60000); // 每分钟检查一次
采用JWT等无状态认证方式:
// 请求时带上token
$.ajax({
url: '/api/data',
headers: {
'Authorization': 'Bearer ' + localStorage.getItem('token')
}
});
通过以上方法,可以有效处理AJAX调用中的会话超时问题,提升用户体验和系统安全性。