我真的很想提醒我的用戶在會話到期前保持會話不變。如何用JavaScript實現會話到期提醒?
昨天我問了一個問題「How can I check if the session is dead, then prompt an alert?」,有人回答了一個AJAX/JSON解決方案,每30秒就會向一個ASP頁面發出調用。這不起作用,因爲對服務器的調用使會話保持活動 - 所以它永遠不會註銷。
我一直在閱讀並且遇到類似的[SO]問題,其中有人建議使用JS倒計時提醒用戶續訂會話,在會話到期前5分鐘。
這是我迄今所做的不過:
- 功能
startMainTimer
似乎並沒有被保持的時間,因爲我沒有收到警報時,計時器是由於提醒。 $('body').mousedown()
功能無法正常工作。它可以工作,但是如果用戶點擊一個鏈接,mousedown函數就可以工作,但不會在函數運行後跟隨鏈接。
下面的代碼:
<script>
$(document).ready(function() {
$.ajax({ // get session expiration value e.g. 60
type : 'GET',
url : '../getSessionValue.asp',
dataType : 'text',
success : function(data) {
if (data != '') {
var newSessionValue = data - 5
startMainTimer(newSessionValue * 60000); // deduct 5 minutes, convert to mSeconds & call startNewTimer()
}
}
});
$('body').mousedown(function() { // if user clicks anywhere on page call ajaxRenewSession() function
ajaxRenewSession();
});
$('#userButtonRenewSession').click(function() { // if user clicks continue browsing button
ajaxRenewSession();
});
});
function startMainTimer(newSessionValue,restart) {
if (restart == 'yes') {
clearInterval(interval);
}
var counter = 0;
var interval = setInterval(function() {
counter++;
if (counter == newSessionValue) {
alert("Your session is about to expire!");
clearInterval(interval);
}
}, 1000);
}
function ajaxRenewSession() { // AJAX the server to renew session, get session timeout value and then reset JS timer
$.ajax({
type : 'GET',
url : '../renewSession.asp',
dataType : 'text',
success : function(data) {
if (data != '') {
var newSessionValue = data - 5
startMainTimer(newSessionValue * 60000, 'yes');
}
}
});
}
</script>
任何人可以幫助我糾正這些問題呢?
這是一個http://codereview.stackexchange.com問題。 – 2012-01-08 15:10:05
我不知道有一個代碼審查網站 – TheCarver 2012-01-08 15:12:25
我也花了幾分鐘或幾秒鐘的時間,將其添加到當前客戶端的機器時間,然後輪詢以查看其中一個是否大於另一個。您只需確保始終爲每個保持會話活動的服務器請求(AJAX,常規頁面請求等)更新該時間。將它保存在cookie中可能是最簡單的方法。 – 2012-01-08 15:12:33