在 Javascript 中刷新 Java 会话对象
我正在尝试使用 javascript 在检测到会话对象发生更改后执行某些操作。但是,在我调用 UpdateServlet 后,javascript 没有检测到会话对象的更改。所有这些都是在同一页面上完成的(即没有页面刷新)
请帮忙!谢谢。
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
}
I am trying to use javascript to do something once 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
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您必须使用 Ajax 才能检查此更改。您可以使用
setInterval
定期检查,如下所示:我的建议是使用 POST 方法进行 ajax 调用以避免缓存(如果缓存,则不会检测到任何更改)
希望这会有所帮助。干杯
PS:我使用 jQuery 因为我看到你在你的代码中使用它
You have to use Ajax in order to check this change. You could check periodically with
setInterval
like this: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