Recently, jsp was used as a website, which involved interchange between java variables and javascript variables. Although there are many materials on the Internet, there are different opinions, and many of them are misleading and many attempts have been made, finally, I understood the problem clearly. In other words, java code runs on the server. The returned value is static on the page, while javascript is a script language and runs on the client! They are two completely different languages, and variables cannot be exchanged directly. However, variables can be transmitted in a certain way.
The java variable is passed to the javascript variable. This is relatively simple, just like the common method:
Copy codeThe Code is as follows:
Var cnt = <% = number %>;
Do not miss the equal sign! This is okay.
Passing javascript variables to Javab variables is a little complicated, but it is easy to understand the principle. Here we mainly get and operate through form submission and form elements:
Copy codeThe Code is as follows:
<Script language = "javascript">
Function button_click (cnt ){
++ Cnt;
Document. submitForm. msg. value = cnt;
Document. submitForm. submit ();
}
</Script>
Copy codeThe Code is as follows:
<%
Number = request. getParameter ("msg ");
If (number = null)
Number = "1 ";
RdData. setIndex (number );
RdData. readData ();
Out. println ("<br/> ");
Out. print (RdData. getIndex () + ".");
Out. print (RdData. getTitle ());
Out. println ("<br/> ");
Out. println ("A." + RdData. getStrA ());
Out. println ("<br/> ");
Out. print ("B." + RdData. getStrB ());
Out. println ("<br/> ");
Out. print ("C." + RdData. getStrC ());
Out. println ("<br/> ");
Out. print ("D." + RdData. getStrD ());
%>
<Input name = "index" type = "text" value = "<% = RdData. getIndex () %>"/>
<Input type = "button" value = "btn" name = "bt" onclick = "button_click (<% = number %>)">
<Form name = "submitForm">
<Input type = "hidden" name = "msg" value = <% = RdData. getIndex () %>/>
</Form>
Pay special attention to the form and javascript code section! Use the hidden elements of the form to pass a data retrieved from the database to the processing function. After performing related operations, submit the form. If the java code is obtained through request. getParameter (), it will be OK ~~~ In fact, the variable is not synchronized at the time, because the function I want to implement is to add a counter and perform a read operation on the database every time I click the button, if the counters are inconsistent, the read order is directly caused. refreshing the page can solve the problem, but it is not a good way to refresh the page all the time. So I want to pass in a parameter. OK.