Here, suppose the reader understands the basic
Ajax
Technology or more. I'm just explaining a phenomenon, a solution, a reason,
Principle, equally not clear
......
Let's start with a simple start,
Servlet passes value to JSP page JS
Script, you use a script to display related values on the page. Solve this direction (servlet--javascript) of Chinese garbled problem is very simple. Only need to be
Servlet, add a
Encoding settings:
Copy Code code as follows:
Response.setcontenttype ("Text/html;charset=utf-8");
and JSP page encoding can be set arbitrarily, GBK, GB2312, UTF-8, of course
Iso-8859-1 is no good, at least you want to display Chinese on the page.
From the JS script to the servlet, the problem is in the XMLHTTP Object Open () method, the transfer value (GET, POST) different, and divided into two cases:
Before you introduce this issue, show the difference between the two ways of passing values:
Suppose the transfer value "software Engineering", the variable is named "Selcol".
1, Get Method:
Copy Code code as follows:
function Selectcol () {
Createxmlhttprequest ();
var selcol = "
Software
Copy Code code as follows:
";
var url = "/emp/findspecial?selcol=" + selcol;
Xmlhttp.onreadystatechange = Handlestatechange;
Xmlhttp.open ("Get", url,true);
Xmlhttp.send (NULL);
}
2, POST method:
Copy Code code as follows:
function Selectcol () {
Createxmlhttprequest ();
var selcol = "selcol= Software engineering";
var url = "/emp/findspecial";
Xmlhttp.onreadystatechange = Handlestatechange;
Xmlhttp.open ("POST", url,true);
Xmlhttpxmlhttp.setrequestheader ("Content-type", "application/x-www-form-urlencoded");
Xmlhttp.send (Selcol);
}
If you use a Get method to pass, then when the servlet takes a value, we encode it in the following way:
Copy Code code as follows:
String selcol = new String (Request.getparameter ("Selcol"). GetBytes ("Iso-8859-1"), "GBK");
Turn GBK, GB2312 all line, turn UTF-8 not!
This time you may be surprised to find that both statements appear at the same time:
Copy Code code as follows:
Response.setcontenttype ("Text/html;charset=utf-8");
String selcol = new String (Request.getparameter ("Selcol"). GetBytes ("Iso-8859-1"), "GBK");
The individual understands this: the first sentence only guarantees that the data encoded by the servlet is UTF-8;
The latter, however, converts incoming data into GBK encoded data. Convenience and identification and processing.
If you use post to pass, then when the servlet takes the value, ditto, just convert the code to UTF-8,
And this time, GBK and GB2312 not!
Copy Code code as follows:
String selcol = new String (Request.getparameter ("Selcol"). GetBytes ("Iso-8859-1"), "UTF-8");