Refresh Java session object in Javascript
I am trying to use javascript to do something onc开发者_运维知识库e it detects a change in the session object. However, javascript does not detect the change in the session object after i have called UpdateServlet. All these is done on the same page (ie. there is no refreshing of page)
Please help! Thanks.
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
}
You have to use Ajax in order to check this change. You could check periodically with setInterval like this:
setInterval(function(){
   //Here goes your ajax call
   $.ajax({
     ...
     type: 'post',
     success: function(data){
        ...            
        if(objectChanged){
           //Do your stuff here
        }  
     }
   });
}, 5000); //Check each 5 seconds
My advice is to do your ajax call with POST method to avoid caching (if it caches, no change will be detected)
Hope this helps. Cheers
PS: I used jQuery cause I saw you were using it on your code
 
         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论