Examples of Get and post public garbled solutions when jQuery calls AJAX

Source: Internet
Author: User

In the past, I wrote about the garbled solution of Get and post when js calls AJAX in Sina Blog, but it is complicated to use js Code, when using ajax for data interaction, we can use jQuery, a mature framework of js.

For the design of a website, you must submit parameters to the server to obtain the required page data, whether you are registering for Logon or querying by page. To reduce the suffering caused by PAGE refreshing, ajax was born. However, beginners may encounter an annoying problem during project development: Chinese garbled characters.

Next I will use a simple example to tell you where garbled characters may occur and how to solve them.
In this example, the username is correct (already exists) during user registration. When the username text is removed from the focus, the username is asynchronously submitted and extracted and determined by the servlet, return the result to the page with a prompt.

Step 1: create a web project (in GBK format by default) named jQuery_Ajax. Create a js package in its WebRoot directory and place the jquery-1.4.4.js in it.

Step 2: Create a servlet package under src and write Vali. javaCopy codeThe Code is as follows: package servlet;
Import java. io. IOException;
Import java. io. PrintWriter;
Import java.net. URLDecoder;
Import javax. servlet. ServletException;
Import javax. servlet. http. HttpServlet;
Importjavax. servlet. http. HttpServletRequest;
Importjavax. servlet. http. HttpServletResponse;
Public class Vali extends HttpServlet {
@ Override
Protectedvoid service (HttpServletRequest request, HttpServletResponse response)
ThrowsServletException, IOException {
StringuserName = URLDecoder. decode (request. getParameter ("userName"), "UTF-8 ");
System. out. println (userName );
Response. setContentType ("text/html; charset = UTF-8 ");
PrintWriter pw = response. getWriter ();
If (userName. equals ("Michael ")){
Pw. println ("error ");
} Else {
Pw. println ("correct ");
}
}
}

From the code, we can see that statements containing the encoding format are one of the solutions to garbled code.
Note in the Code:
1. URLDecoder. decode (request. getParameter ("userName"), "UTF-8") -- convert and extract data from the page
2. response. setContentType ("text/html; charset = UTF-8") -- encode the response returned value in UTF-8 and return the page
3. Note that the conversion in step 2 should be written before the response of everything in this method. Otherwise, the conversion may fail.
4. This servlet only applies to the Post Method for Data Format encoding. If the submission method is GET, the code for extracting page data is as follows:Copy codeThe Code is as follows: request. setCharacterEncoding ("UTF-8 ");
StringuserName = request. getParameter ("userName ");
UserName = new String (userName. getBytes ("iso-8859-1"), "UTF-8 ");

Step 3: Compile the simple registration page ajax. jspCopy codeThe Code is as follows: <% @ page language = "java" import = "java. util. *" pageEncoding = "UTF-8" %>
<%
String path = request. getContextPath ();
String basePath = request. getScheme () + ": //" + request. getServerName () + ":" + request. getServerPort () + path + "/";
%>
<! Doctype html public "-// W3C // DTDHTML 4.01 Transitional // EN">
<Html>
<Head>
<Base href = "<% = basePath %>">
<Title> My JSP 'ajax. js' starting page </title>
<Metahttp-equiv = "pragma" content = "no-cache">
<Metahttp-equiv = "cache-control" content = "no-cache">
<Metahttp-equiv = "expires" content = "0">
<Metahttp-equiv = "keywords" content = "keyword1, keyword2, keyword3">
<Metahttp-equiv = "description" content = "This is my page">
<! --
<Linkrel = "stylesheet" type = "text/css" href = "styles.css">
-->
<Scripttype = "text/javascript" src = "js/jquery-1.4.4.js"> </script>
<Scripttype = "text/javascript">
Function vali (){
$. Ajax ({
Type: "POST ",
Url: "/jQuery_Ajax/Vali ",
Data: encodeURI ("userName =" + $ (": text"). val ())),
Success: function (data ){
$ ("Span"). text (data );
}
});
}
</Script>
</Head>
<Body>
UserName: <inputtype = "text" name = "userName" onblur = "vali ();"/> <span> </span> <br/>
Password: <inputtype = "password" name = "password"/>
</Body>
</Html>

Note in the Code:
1. The page should be set to UTF-8 and introduce jquery-1.4.4.js
2. ajax transmits data through the POST method. Pay attention to the data settings. Enter the returned data in the span tag.

If you use the GET method to pass page data, the js Code is as follows:Copy codeThe Code is as follows: function vali (){
$. Ajax ({
Type: "GET ",
Url: "/jQuery_Ajax/Vali ",
Data: encodeURI ("userName =" + $ (": text"). val ()),
Success: function (data ){
$ ("Span"). text (data );
}
});
}

The last step is to configure servlet and ing in web. xml.Copy codeThe Code is as follows: <servlet>
<Description> This is the description of my J2EEcomponent </description>
<Display-name> This is the display name of my J2EEcomponent </display-name>
<Servlet-name> Vali </servlet-name>
<Servlet-class> servlet. Vali </servlet-class>
</Servlet>
<Servlet-mapping>
<Servlet-name> Vali </servlet-name>
<Url-pattern>/Vali </url-pattern>
</Servlet-mapping>

After the above Code is compiled, this registration and verification project has been completed, deployed to tomcat and accessed through the web page.

Finally, we will summarize the solutions to jQuery Garbled text.:
1. Check the page encoding and set the page encoding to utf8 as follows:
<Metahttp-equiv = "content-type" content = "text/html; charset = UTF-8">
2. Check the servlet and add the following code to the doPost or doGet method:
Response. setContentType ("text/xml; charset = UTF-8 ");
3. Modify the tomcat file and add URIEncoding = "utf8" to the TOMCAT_HOME/conf/server. xml file ":
<Connector port = "8080" protocol = "HTTP/1.1" connectionTimeout = "20000" redirectPort = "8443" URIEncoding = "UTF-8"/>
4. Add a filter in the project and set the encoding method to utf8.
After the above four steps, the problem persists.
5. Check the http header of ie and view the contentType field as follows:
ContentType: "application/x-www-form-urlencoded"
6. Check the http header of firefox and view the contentType field as follows:
ContentType: "application/x-www-form-urlencoded; charset = UTF-8"
Compared with Step 5 and step 6, the problem occurs.
7. Modify the jQuery-1.x.x.js file
ContentType: "application/x-www-form-urlencoded" changed to the following code:
ContentType: "application/x-www-form-urlencoded; charset = UTF-8"

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.