我寫了一個小的jQuery代碼,如果頁面未刷新1800秒,將顯示一個對話框。會話自動結束前,對話框會倒計時。如果用戶點擊「是,繼續工作」,則計數器重置,對話框消失。否則,用戶將被轉移到註銷頁面。如何使用ajax請求更改setTimeout()計數器?
我在這裏遇到的問題是用戶打開新瀏覽器的選項卡並繼續在新選項卡上工作。然後,舊標籤將在「1800秒後無刷新」時變爲空閒狀態,因此它們將所有會話都鬆開並註銷。
我已經創建了一個PHP頁面,它將通過使用$_SESSION
信息檢查數據庫中的時間來返回剩餘的秒數。但我不確定如何重置對話框打開時的計數器。
我不確定如何修改我的代碼以檢查顯示對話框之前剩餘的實際秒數。
這裏是我的代碼
<!-- This script will alert a user before forcing to logout -->
<script type="text/javascript">
var timer;
var closeDialogAfter = 180; //The default counter value
var idleTimeOutLimit = 1800 - closeDialogAfter; //Display the dialog after @idleTimeOutLimit seconds of idle time
var signOutScript = '/index.php?action=logout'; //logout url
var keepAliveScript = '/ajax/handler-keep-me-alive.php'; //php page to handle ajax request to keep the session alive
var dialogCountdown = '#dialog-countdown'; // the lable that is used to display the counter
var idleTimeout= '#idleTimeout'; //the div that is used for the dialog
$(function(){
//start the idle time out counter
startTimeoutCounter();
$(idleTimeout).dialog({
resizable: false,
autoOpen: false,
width: 400,
open: function(){
updateTimeoutCounter();
},
buttons: {
"Yes, Keep working": function(e) {
$.ajax({
url: keepAliveScript,
success: function(data) {
startTimeoutCounter();
$(idleTimeout).dialog("close");
}
});
},
"No, End Session": function(e){
forceLogOut();
$(this).dialog('close');
}
}
});
});
function startTimeoutCounter(){
timer = closeDialogAfter;
$(dialogCountdown).text(timer);
setTimeout(function(){
$(idleTimeout).dialog("open");
}, idleTimeOutLimit * 1000);
}
function updateTimeoutCounter(){
if( $(idleTimeout).dialog("isOpen")){
setTimeout(function(){
timer = timer -1;
$(dialogCountdown).text(timer);
(timer < 2) ? forceLogOut() : updateTimeoutCounter();
}, 1000);
} else
$(dialogCountdown).text(closeDialogAfter)
}
function forceLogOut(){
window.location = signOutScript;
}
</script>
嘗試使用localstorage設置跨標籤的剩餘時間 – juvian 2014-10-06 21:22:38
@juvian如何使用本地存儲? – Jaylen 2014-10-06 21:33:39
標籤是什麼意思? – 2014-10-06 21:36:00