Ajax garbled solution Summary

Source: Internet
Author: User
Ajax garbled solution Summary
First, JavaScript follows the Java character processing method, and Unicode is used internally to process all characters,
Second, UTF-8 is stored in three bytes for each Chinese character (UNICODE character.
Third, garbled characters are not generated when UTF-8 is used to send data. garbled characters are generated only when the background program does not properly decode the data.
Fourth, when Ajax sends data, if the Content-Type is modified to application/X-WWW-form-urlencoded ", it must be post, however, "Too large data may often go wrong" is caused by the use of get to send data.
Fifth, the function written with VBScript is used to convert data into GBK encoding (the default encoding method of the operating system. If big5 is used in traditional Chinese systems, instead of gb2312, the number of characters in the two codes varies by about three times.
Sixth, use cookies to send data. First, it is easy to overflow, and second, it is necessary to keep wiping your ass. Otherwise, the data in the cookie is stored in each HTTP Request (including image and script requests) will be sent. Third, when several HTTP requests are concurrently sent, there is no way to specify the cookie to be sent to that HTTP request.
------------------------
When Ajax is used to get back to a page, most of the Chinese characters in responsetext will be garbled, this is because XMLHTTP in processing the returned responsetext, is the resposebody according to the UTF-8 encoding into the decoding test form, if the server sends a data stream that is indeed a UTF-8, the Chinese characters will be correctly displayed, and when the GBK encoding stream is sent out, it will be messy. The solution is to add a header in the sent stream to specify the encoding stream to be sent, so that XMLHTTP will not be messed up.

PHP: Header ('content-type: text/html; charset = gb2312 ');
ASP: Response. charset ("gb2312 ")
JSP: Response. setheader ("charset", "gb2312 ");Method 1(This method is not very reliable) send a request to the server and add the following to the server:
String string = request. getparmater ("parmater ");
String = new string (string. getbytes ("ISO8859-1"), "GBK ");
The server sends messages to the client:
String static content_type = "text/html; charset = GBK ";
Response. setcontenttype (content_type );Method 2(Not recommended, urldecoder. Decode () is incompatible with the new browser.) solve Chinese garbled characters in Ajax post

After reading many articles, I finally saw an article that solved my own problems.

Ajaxpost. js

VaR myrequest; // variable to hold request object
Function mysubmit ()...{
If (window. XMLHttpRequest)
...{
Myrequest = new XMLHttpRequest (); // Standards-compliant browsers
} Else if (window. activexobject)
...{
Myrequest = new activexobject ("msxml2.xmlhttp"); // for IE
}

VaR post = "name =" + document. getelementbyid ("postval"). value;
Post = encodeuri (post );
Post = encodeuri (post); // the most important part. Two calls to encodeuri are encoded twice.
Myrequest. Open ("Post", "Servlet/display", false );
// Myrequest. setRequestHeader ("contentlength", post. Length );
Myrequest. setRequestHeader ("Content-Type", "application/X-WWW-form-urlencoded ");
Myrequest. Send (post );
VaR res = myrequest. responsetext; // receives the returned data
Document. getelementbyid ("display"). innerhtml = res;
}

Servlet

Public void dopost (httpservletrequest request, httpservletresponse response)
Throws servletexception, ioexception ...{

Response. setcontenttype ("text/html ");
Response. setcharacterencoding ("GBK ");
Printwriter out = response. getwriter ();
String name = request. getparameter ("name ");
Name = urldecoder. Decode (name, "utf8"); // when the post is passed, it must be UTF-8 encoded. You can set the URL by yourself.
System. Out. println (name );
Out. println (name );
Out. Flush ();
Out. Close ();
}

Analysis: When the request. getparameter () function is called, The URI decoding process is automatically performed. The built-in decoding process during the call may cause garbled characters. After URI encoding twice, the request. getparameter () function obtains the content encoded once by the original information Uri. You can use the controllable decoding function java.net. urldecoder. Decode () to obtain the original correct information.

Method 3(Yes)

Solution for returning garbled data when submitting Ajax data
With the popularity of Ajax, The Garbled text problem also began to plague many programmers who started to use it. Fortunately, I have studied JSP Garbled text before. After encountering Ajax, it has not brought me much trouble. Here I will share some of my experiences with you.
The problem of Ajax garbled characters is naturally related to encoding. In fact, many people think of setting file encoding like me, and set requet encoding when receiving data, when the returned data is encoded with response, everything is thought to be smooth, but this is all futile, and the nasty garbled code appears again in front of you. After you try n methods, including JS's own escape and Unescape methods, you find garbled characters still appearing on the screen.
In fact, after trying these n methods, many people have not found that the solution is actually very simple, and the answer lies in the JSP garbled code we have previously processed. Let's take a look at the typical Ajax request code.

Finally, do not forget to set it when returning data:

XMLHTTP. Open ("Post", URL, async );
XMLHTTP. setRequestHeader ("Content-Type", "text/html ");
XMLHTTP. Send (Params );

According to the previous instructions, I don't know if you can see it now. I don't know whether it is affected by the online tutorials or other aspects. The setRequestHeader remains unchanged for years, and no one wants to change it. The problem lies exactly in this place. Recall the encoding settings of the content of a JSP page, which includes the following section:

Contenttype = "text/html; charsets = UTF-8"

Now we know the problem, so we need to change the second code:

XMLHTTP. setRequestHeader ("Content-Type", "text/html; charset = UTF-8 ");

 

Response. setcontenttype ("text/XML ");
Response. setcharacterencoding ("UTF-8 ");

Isn't it easy?
To ask why, we can regard XMLHTTP as a temporary page, which is dynamically generated by the browser, the main function is to obtain the requested data in the background (it can be considered as an advanced IFRAME ). Therefore, you must also set the encoding for common pages. Why do you set contenttype and encoding for the returned data in Servlet. As we all know, the final form of JSP is servlet, And the content set in the JSP header is actually to generate the following two sentences in the generated servlet:

Response. setcontenttype ("text/html ");
Response. setcharacterencoding ("UTF-8 ");

Pageencoding demonstrates the encoding used for saving the content of the page with JVM (this is related to the generated class ). Therefore, the response encoding in servlet is also taken for granted.

 Method 4(It's safe, but the code is huge, which is a good choice .)

Before sending an Ajax request, request the parameter escape () twice (for example, name = escape ("James");), and then send the request to the server, after receiving the parameters, the server can obtain the correct parameters (for example, string name = Unescape (request. getparameter ("name "));).

Java version of scape implementation

Public static string Unescape (string SRC)
...{
Stringbuffer TMP = new stringbuffer ();
TMP. ensurecapacity (SRC. Length ());
Int lastpos = 0, Pos = 0;
Char ch;
While (lastpos <SRC. Length ())
...{
Pos = SRC. indexof ("%", lastpos );
If (Pos = lastpos)
...{
If (SRC. charat (Pos + 1) = 'U ')
...{
Ch = (char) integer. parseint (SRC. substring (Pos + 2, POS + 6), 16 );
TMP. append (CH );
Lastpos = POS + 6;
}
Else
...{
Ch = (char) integer. parseint (SRC. substring (Pos + 1, POS + 3), 16 );
TMP. append (CH );
Lastpos = POS + 3;
}
}
Else
...{
If (Pos =-1)
...{
TMP. append (SRC. substring (lastpos ));
Lastpos = SRC. Length ();
}
Else
...{
TMP. append (SRC. substring (lastpos, POS ));
Lastpos = Pos;
}
}
}
Return TMP. tostring ();
}

Appendix: solution to prototype Ajax garbled code (tested and feasible)
Prototype encodes the passed parameters. Each transmitted value is processed by encodeuricomponent. the encoding will be converted to UTF-8. When obtaining the request in the background, the request should be used in a unified manner. setcharacterencoding ("UTF-8") sets the encoding for the request without having to worry about what the page encoding format is. if the post method is used to transmit data, the system will automatically execute:
Request. setheader ('content-type', 'application/X-WWW-form-urlencoded'). Ensure that the data encoding format is correct.

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.