2010-10-07 55 views
13

我有一個會話超時時間爲15分鐘的網站。在某些頁面上,用戶偶爾會花費超過15分鐘的時間填寫回復。在這種情況下保持活動的最佳解決方案是什麼?如何讓用戶的會話在論壇上發佈時保持活躍狀態​​?

我已經在這些頁面上使用JQuery,所以可能ping一個服務器,但是在什麼事件上?

後端是Tomcat上的Struts

+0

15分鐘似乎非常短。你不能只是增加超時時間嗎? – Eli 2010-10-07 00:56:55

回答

24

給你不想改變網站的會話超時..

在JavaScript設置超時/間隔(< 15分鐘)的事件,並決定在事件觸發時該怎麼辦。如果您希望會話在頁面打開的情況下處於活動狀態,那麼很好,請在每個<的15分鐘內持續ping。但是,這可能不是你想要的,因爲離開公共計算機的用戶應該在某個時候註銷。

您可以維護一個變量lastActivity,該變量在每個文檔mousemove或文檔keydown上更新。如果自上次ping之後還有任何活動,請再次ping。

要想獲得更復雜的結果,只有在事件數大於閾值超時的情況下,才能計數事件並ping服務器。

基本例如:

setInterval(function(){ 
    $.get('/ImStillAlive.action'); 
}, 840000); // 14 mins * 60 * 1000 

隨着輸入活動的基本檢查:

$(function(){ 
    var lastUpdate = 0; 
    var checkInterval = setInterval(function(){ 
     if(new Date().getTime() - lastUpdate > 840000){ 
      clearInterval(checkInterval); 
     }else{ 
      $.get('/ImStillAlive.action'); 
     } 
    }, 840000); // 14 mins * 60 * 1000 

    $(document).keydown(function(){ 
     lastUpdate = new Date().getTime(); 
    }); 
}); 
+1

如果用戶笨拙地走開離開瀏覽器打開並登錄,我不會打擾。 – casablanca 2010-10-07 00:24:36

+0

謝謝,這似乎是一個很好的方法來做到這一點。 – Nick 2010-10-07 22:33:56

0

你可以設置的時間間隔過5分鐘:

setInterval(function() { 
    // check if a reply textarea is present on the page and focussed 
    // assuming it's e.g. a textarea with the id "reply" 
    if ($('#reply:focussed').length) { 
     // user is still on the reply page 
     // call on a script on the server that renews the session 
    } 
}, 300000);

或者檢查是否他/她仍然在打字:

<textarea id="reply"></textarea> 
<input type="hidden" id="reply_length" name="length" />
setInterval(function() { 
    // get length of text in textarea 
    var len = $('#reply').val().length; 

    // get previous length 
    var prev = $('#reply_length').val().length; 

    // if they don't match, assume they're doing something 
    if (len != prev) { 
     // renew session 
    } 

    // update previous length 
    $('#reply_length').val(len); 
}, 300000);
3

我在想,你真的不希望爲所有的頁面,但儘管如此。如果你要在每一頁上這樣做,即使是那些真的不依賴會話變量的人,你也會消耗大量的內存。

我建議在有條件投擲做只在特定網頁,這是必要的,即

if (location.href.indexOf('/checkout') !== -1) { 
setInterval(function(){ 
    $.get('/keepalive.action'); 
}, 840000); // 14 mins 
} 
相關問題