大家好我试图制作一个观众计数器,用于存储访问该网站的总观众的价值。为此,我维护一个名为counter的表,其中我存储了查看者的值。但是我也不想通过多次页面刷新来更新查看者的值,所以我将一个键放入localstorage中,并且在页面刷新检查期间,如果已经设置了该键,我只需从中检索该值数据库,如果密钥不存在,数据库值将增加1.
if(localStorage.getItem("counter")===null)
{
<%
Connection con = ConnectionManager.getConnection();
PreparedStatement ps = con.prepareStatement("Select views from counter");
ResultSet rs = ps.executeQuery();
long viewers=0;
if(rs.next())
{
viewers = rs.getLong("views");
}
viewers = viewers+1;
ps = con.prepareStatement("update counter set views = ?");
ps.setLong(1,viewers);
int update = ps.executeUpdate();
%>
var v =document.getElementById("v");
v.innerHTML = <%= viewers %>;
localStorage.setItem("counter",<%= viewers %>) ;
}
else{
<%
con = ConnectionManager.getConnection();
ps = con.prepareStatement("Select views from counter");
rs = ps.executeQuery();
long counts=0;
if(rs.next())
{
counts = rs.getLong("views");
}
%>
var v =document.getElementById("v");
v.innerHTML=<%= counts %>;
}
但我无法弄清楚为什么即使在localStorage中设置了密钥,数据库的值也会增加。如果你有更好的想法,请建议我这样做。
谢谢!