2011-07-07 51 views
0

我想在JavaScript檢測到會話對象發生變化時使用javascript來做某件事。但是,在調用UpdateServlet之後,javascript並未檢測到會話對象中的更改。所有這些都是在同一頁面上完成的(即沒有刷新的頁面)使用Javascript刷新Java會話對象

請幫忙!謝謝。

的index.jsp

<% 
    //initial settings 
    session.setAttribute("dataUpdated", "false"); 

%> 
<script> 

    $(function() { 
     var updates = '<%=session.getAttribute("dataUpdated")%>'; 

     alert(updates); 
     //Shows false even after update 

     if (updates=="true"){ 
      //alert("Updated"); 
     } 



    }); 
</script> 

UpdateServlet.java

protected void doPost(HttpServletRequest request, HttpServletResponse response) 
     throws ServletException, IOException { 

     HttpSession session = request.getSession(); 
     session.setAttribute("dataUpdated", "true"); 
     //session object set to true 

} 

回答

1

你必須以檢查這種改變使用Ajax。你可以用setInterval這樣的定期檢查:

setInterval(function(){ 
    //Here goes your ajax call 
    $.ajax({ 
    ... 
    type: 'post', 
    success: function(data){ 
     ...    
     if(objectChanged){ 
      //Do your stuff here 
     } 
    } 
    }); 
}, 5000); //Check each 5 seconds 

我的建議是做POST方法的調用Ajax避免緩存(如果緩存,沒有任何變化都會被檢測到)

希望這有助於。乾杯

PS:我用jQuery的原因,我看到你在你的代碼上使用它

+0

這就是對的!謝謝!現在,我還有一個問題,我需要在成功函數後將會話對象重置爲false。我怎麼做? 我試過如果 (objectChanged){<%= session.setAttribute(「dataUpdated」,「true」)%>} 但它不起作用。我必須再次使用AJAX嗎? – newtodatatables

+0

是的,你會再次需要ajax,但最好是在同一個ajax調用中重置服務器上的會話對象,所以你可以將邏輯'if(objectChanged)...'移動到服務器。 –

+0

哦,你是對的。最好重置servlet端的對象。謝謝你的提示。 – newtodatatables