jquery get and post common garbled solution when calling Ajax

Source: Internet
Author: User
Tags tomcat

Before the Sina blog wrote JS call Ajax get and post garbled solution, but the use of JS code is cumbersome, we use AJAX for data interaction can use a mature framework of JS---jQuery.

The design of a Web site, whether registered or paged, requires the submission of parameters to the server to obtain the required page data. In order to reduce users due to refresh the page caused by the suffering, Ajax was born. But in the beginning of the project development, will encounter a very annoying problem: Chinese garbled.

Here I have a simple example to tell you which places can lead to garbled characters, we need to solve by what way.

Our example mainly implements user registration when the user name is correct (already exist), when the focus shifted the text username, the username asynchronous commit and the servlet extract judgment, and the results returned to the page to make the appropriate prompt.

The first step is to create a new Web project (the default GBK format), named Jquery_ajax. Create a new JS package in its Webroot directory and put the jquery-1.4.4.js in it.

In the second step, create the servlet package under SRC and write the Vali.java

  
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 ("Zhang San")) {
pw.println ("error");
} else{
pw.println ("correct");}}}


From the code can be seen, contains the encoding format of the statement is one way to solve garbled.

Note In the code: 1. Urldecoder.decode (Request.getparameter ("UserName"), "Utf-8")--convert the data from the page to format and extract

2.response.setcontenttype ("Text/html;charset=utf-8")--Return to page after encoding the response return value Utf-8

3. Special note that the conversion in 2 must be written before all response in this method, otherwise it may fail

4. This servlet format encoding data is only suitable for the Post method, if the submission method is get, the code to extract the page data is as follows:

     Request.setcharacterencoding ("Utf-8");
                   Stringusername = Request.getparameter ("UserName");
                   Username= New String (Username.getbytes ("iso-8859-1"), "Utf-8");
 

The third step is to write a simple registration page ajax.jsp

 <%@ 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" >  


Note In the code: 1. The page to be set to Utf-8, and the introduction of Jquery-1.4.4.js

2.ajax Pass the data through the Post method, noting the settings Fill in the span label with the returned data.

If you use the Get method to pass page data, the JS 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 final step is to configure the servlet and mappings on the Web. xml

<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 code has been written, this registration-validated project has been completed, deployed to Tomcat and accessed through the Web.

Finally summarizes the great God's jquery garbled problem solves the method:

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 to 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 to set the encoding mode to UTF8

After the above four steps, the problem remains.

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 5, 62 steps, the problem arises.

7. Modify the Jquery-1.x.x.js file to

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.