问题
I have two buttons, one called "Previous" the other is called "Next". When they are clicked, they reload the JSP page in which they are defined. They are also supposed to either increment or decrement a variable.
<form name="input" action="MyPage.jsp" method="post">
<html>
<input type="submit" value="Previous" onclick="<% hitsCount--; %>">
</html>
<html>
<input type="submit" value="Next" onclick="<% hitsCount++; %>">
</html>
The problem I am having is that I cannot figure out how to define the variable in such a way that it is not reset each time the page loads.
For example if "hitsCount" is 0, and I click the "Next" button the page should reload and the value of "hitsCount" should be incremented by one. The next time I hit the "Next" button, the page reloads and "hitsCount" should contain a value of 2.
回答1:
you can use session storage for keep the values in the client side
Here is a link where you can see how session storage works.
回答2:
You could always use html5 local storage:
var hitsCount = localStorage.getItem("hitsCount");
localStorage.setItem("hotsCount", hitsCount++);
If the user is using an older browser that doesn't support local storage, try setting a cookie instead. If you don't like either of these options then you'll have to pass the hitsCount variable to the next screen using a url paramater.
来源:https://stackoverflow.com/questions/20059712/how-to-create-a-jsp-variable-that-does-not-reset-on-page-reload