jquery call Ajax when get and post public garbled

Source: Internet
Author: User
Tags tomcat

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

  The design of a website, whether registering or paging, requires submitting parameters to the server to get the required page data. In order to reduce the user caused by refreshing the suffering of the page, Ajax was born. But when a beginner develops a project, it will encounter a very annoying problem: Chinese garbled.   Below I will use a simple example to tell you which places can lead to garbled, we need to solve in what way.   Our example is the main implementation of user registration when the user name is correct (already exists), in the focus of the username text, the username asynchronous submission and the servlet to extract the judgment, and the results returned to the page to make the appropriate prompts.   The first step, create a new Web project (default GBK format), named Jquery_ajax. Create a new JS package in its Webroot directory and place the jquery-1.4.4.js in it.     Step Two, create a servlet package under SRC and write vali.java    code 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");nbsp System.out.println (userName);  response.setcontenttype ("Text/html;charset=utf-8");  PrintWriter = Response.getwriter ();  if (Username.equals ("John")) {  pw.println ("error"); }else{  ("correct") ; } } }    from the code can be seen in the coding format of the statement is one of the ways to solve garbled.   Note In the code: 1.urldecoder.decode (Request.getparameter ("UserName"), "Utf-8")--converts the data from the page to format and extracts   2. Response.setcontenttype ("Text/html;charset=utf-8")--Utf-8 The response return value to return the page   3. Special attention to the conversion in 2 to be written in all the response of this method, Otherwise it may fail   4. This servlet formats the data in a way that is only suitable for post methods, and the code for fetching page data if the submission is get is the following:  copy code code as follows: Request.setcharacterencoding (" Utf-8 ");  Stringusername = Request.getparameter (" UserName ");  username= new String (Username.getbytes (" Iso-8859-1 ")," Utf-8 ");    step Three, write a simple registration page ajax.jsp  code 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.jsp ' 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 are 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 (encodeURI ("Username=" +$ (": Text"). Val ()) ),  success:function (data){  $ ("span"). Text (data); } }); }  </script>  </head>  <body>& nbsp User name: <inputtype= "text" name= "UserName" onblur= "Vali ();" /><span></span><br/>  Password: <inputtype= "password" name= "password"/>  </body >  </html>    In code Note: 1. Page to be set to Utf-8, and introduce jquery-1.4.4.js  2.ajax pass the data through the Post method, pay attention to the settings. Fills the return data into the span label.   If you use the Get method to pass page data, the JS code follows:    code as follows: function Vali () {  $.ajax ({  type: "Get",  URL: "/jquery _ajax/vali ",  Data:encodeuri (" Username= "+$ (": Text "). Val ()),  success:function (data) {  $ (" span "). Text (data); } }); }    Final step, configure the servlet and mapping   code in Web.xml as follows: <servlet>  < Description>this is the description's 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 written, this registration verification project has been completed, deployed to Tomcat and accessed through the Web page.   Finally summed up the great god jquery garbled problem solving method:  1. Check the page encoding to set the page encoding to UTF8, as follows:  <metahttp-equiv= "Content-type" content= "Text/html;charset=utf-8" >  2. Check the servlet, add the following code to the Dopost or Doget method:  Response.setcontenttype ("Text/xml;charset=utf-8");  3. Modify Tomcat files to add uriencoding= "UTF8":  <connector port= "8080" protocol= "HTTP/" in Tomcat_home/conf/server.xml files 1.1 "connectiontimeout=" "20000" redirectport= "8443" uriencoding= "Utf-8"/>  4. The new filter in the project, the encoding mode set to utf8  after the above four steps, the problem remains.   5. Check the HTTP header for IE, and view the ContentType field as follows:  ContentType: "application/x-www-form-urlencoded"   6. Check the HTTP header for Firefox and view the ContentType field as follows:  ContentType: "Application/x-www-form-urlencoded;charset=utf-8" &NBSp Contrast 5, 62 steps, problems arise.   7. Modify the Jquery-1.x.x.js file to change   contentType: "application/x-www-form-urlencoded" 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.