问题描述
今天被坑死了,由于第一次用jstl,结果ajax向后台把session数据保存起来后,但是jstl没有直接的把数据在前台展示,就必须要手动刷新一遍页面才能显示值的问题。
刚开始的解决办法:
我在ajax后面设置了自动刷新,结果进入了死循环,由于刷新后页面还要进行ajax,ajax后还要刷新页面,PASS!
后来经过了无数的测试,我吐了,非常希望大神能告诉有没有已经有的方法解决这个问题!!!
但是我想了一种办法,可以勉强用了。
解决方案
在前台的js中加入这些:
$(document).ready(function () {
<%
Boolean bool=(Boolean) request.getSession().getAttribute("flush");
%>
var flag = <%=bool%>;
console.log(flag);
if (flag == null) {
$.ajax({
async: false,
url: "userPostcardQuery",
type: "post",
success: function (data) {
}
});
window.location.reload();
}
});
后台:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
ArrayList<Postcard> postcards = new ArrayList<>();
User user = (User) request.getSession().getAttribute("user");
String username = user.getUsername();
postcards = postcardDao.findAllByUsernameOrderByUpdateTimeDesc(username);
request.getSession().setAttribute("postcards", postcards);
request.getSession().setAttribute("flush",true);
response.sendRedirect("postcard.jsp");
}
这种解决方法的思路是:
如果我是第一次访问页面,数据还没有放到session中,那么我就调用ajax访问后台,并且后台会把flush保存到session中,这样前台通过判断flush是否刷新来决定是否进行ajax的方法。
由于session一旦保存进去,刷新页面后就不需要再次进行ajax了,这样也不会进入死循环。