Ajax in GB2312 Chinese encoding transmission AJAX special character encoding correct method _ajax related

Source: Internet
Author: User
Tags md5 encryption urlencode
Many may be removed in the course of the transfer of distortion or without verification, real use is not, but also to determine their own all-round test, efforts or not in vain, although the final results are very simple, but its process for a newly-learned Ajax people, really very tired.
You are welcome to use the process of a new experience with a thread exchange, a thought + a thought, can produce at least two ideas.

first, when a get is sent:

Method 1: At the ASP server end with response.charset= "GB2312" defined output encoded to the calling client
At this point the client does not need to do any conversion. The following two files:
1. Client JS
Copy Code code as follows:

var xmlHttp;
function Createxml () {
if (window. ActiveXObject) {
Xmlhttp=new ActiveXObject ("Microsoft.XMLHTTP");
}else if (window. XMLHttpRequest) {
Xmlhttp=new XMLHttpRequest ();
}
}
function Startxml () {
Createxml ();
Xmlhttp.onreadystatechange = Handlestatechange;
var url= "AJAXTEXT.ASP?TM=1&CC" +math.random ();
var sendcontents = ' theinput= ' +escape (theinput.value);
var regcode= "2ABC";
Xmlhttp.open ("Get", url,true);
Regcode= "Regcode=" +regcode;
Xmlhttp.setrequestheader ("Content-length", regcode.length); Can add can not add
Xmlhttp.setrequestheader ("Cache-control", "No-cache");
Xmlhttp.setrequestheader (' Content-type ', ' application/x-www-form-urlencoded '); Can not add
Xmlhttp.send (NULL);
Xmlhttp.send ("regcode=" +escape (Regcode));
Xmlhttp.send (NULL);
}
function Handlestatechange () {
if (xmlhttp.readystate = = 4 && xmlhttp.status==200) {
var Divid=document.getelementbyid ("Results");
Retext=xmlhttp.responsetext;
alert (Retext);
if (Divid.haschildnodes ()) {
Divid.removechild (Divid.childnodes[0]);
//}
var result=document.createtextnode (Xmlhttp.responsetext);
Divid.appendchild (result);
document.getElementById ("Results"). Innerhtml=xmlhttp.responsetext;
}
}

Server side:
Copy Code code as follows:

<%Response.CodePage=936%>
<%response.charset= "GB2312"
Dim reg
Reg=request ("Regcode")
Response.Write "Mr. Wang and his friends" can be correctly exported.
%>

Method 2: Convert the function (from the web) to the client.
Copy Code code as follows:

function Gb2utf8 (data) {
var glbencode = [];
Gb2utf8_data = data;
Execscript ("Gb2utf8_data = MidB (gb2utf8_data, 1)", "VBScript");
var t=escape (gb2utf8_data). Replace (/%u/g, ""). Replace (/(. { 2}) (. { 2})/g, "%$2%$1"). Replace (/% [A-z].)% (. {2}) /g, "@$1$2");
T=t.split ("@");
var i=0,j=t.length,k;
while (++I<J) {
K=t[i].substring (0,4);
if (!glbencode[k]) {
Gb2utf8_char = eval ("0x" +k);
Execscript ("Gb2utf8_char = Chr (Gb2utf8_char)", "VBScript");
Glbencode[k]=escape (Gb2utf8_char). substring (1,6);
}
T[i]=glbencode[k]+t[i].substring (4);
}
Gb2utf8_data = Gb2utf8_char = null;
Return unescape (T.join ("%"));
}

At this point if the server side does not indicate the encoding, then Ajax defaults to UTF-8, can not be displayed on the client, use this function.
Copy Code code as follows:

Retext=xmlhttp.responsetext;
Retext=gb2utf8 (Retext);
alert (Retext);

3, under the Firefox browser: specific please refer to: Next article

Firefox is simpler, he can support Xmlhttp.responsetext;//firefox, but for code simplification, it is recommended to use the above directly to do the coding.
But if you're going to do it for general purpose, do it in the way described below post.

Second, when post send:

For conventional Chinese, the above get method is also available for post, but there is an article on the web that says some of the symbols can't be displayed, such as "Test Test+test" in the next article, (intermediate interval number) tested, It is true that the output to the client is not displayed when the code is defined on the server side.

If, according to the article,
Send End With Xmlhttp.send ("Regcode=" +escape (Regcode));

Then on the server side will receive the data set two encoding encodeURIComponent (Escape (xxxxxxx)), then the result is displayed: Test%25u7a5eest%2520test, also not. In addition, this idea should be wrong, do not know if this article is Shang on the internet is itself wrong, in the client with escape code transmission, the server should be back code. Or the request itself has the function of decoding. No need to encode two or three times. And after checking, escape and encodeuricomponent cannot encode special characters.

I made the following output on the server side:
Copy Code code as follows:

test2= "Test test+test Feedback:"
Response.Write test2& "Before the server is directly output rather than received special symbols" · " Interval number. followed by the data received (the content is the same as the original Ajax sent, for comparison): "

That is to say, the server-side file is generated with the same special character, which is already defined as GB2312 with the <%response.charset= "GB2312"%>. The result of the output, however, is that the server-side generated test2= "Test test+test Feedback:" Can output normally, and the received Ajax value is not.
Even if the client with JS three encoding parameters Escape () \encodeuri () \encodeuricomponent () all tried, and then the server to reverse code and then output, is not. This means that special symbols in a string are distorted when they are received on the server side.

Now the problem is defined in the code transmission, in order to illustrate this issue, I did a small test: is the string assignment to an ASP variable to the ASP variable to assign to JS, as follows:
Copy Code code as follows:

<%
Para= "Test test+test/"
Para=server.urlencode (para)
%>

And then to the JS variable, as follows:
Copy Code code as follows:

Xmlhttp.open ("POST", url,true);
var regcode= "<%=para%>";
Xmlhttp.setrequestheader (' Content-type ', ' application/x-www-form-urlencoded;charset=gb2312 ');
Xmlhttp.send ("regcode=" +regcode);

The result is normal, which fully demonstrates that the server.urlencode of the ASP can encode the special character completely. And JS is still deficient.

So what now?

In a situation where there is no way, I think that encodeuricomponent () can encode more special characters than encode (), so as to add a hardening agent like multiple MD5 encryption, so I applied two encodeuricomponent (), Now the code is:
Copy Code code as follows:

var regcode= "Test test+test/";
Xmlhttp.setrequestheader (' Content-type ', ' application/x-www-form-urlencoded;charset=gb2312 ');
Xmlhttp.send ("regcode=" +encodeuricomponent (encodeURIComponent (Regcode));

Above is the client, and then the server side to:
Copy Code code as follows:

<script language= "javascript" runat= "Server" >
function Decodestr (str) {
Return decodeURIComponent (decodeURIComponent (str));
}
</script>
<%
Dim reg
Reg=request ("Regcode")
test2= "Test test+test Feedback:"
Response.Write test2& "" is preceded by a special symbol, not received, that is entered directly by the service "·" Interval number. followed by the data received (the content is the same as the original Ajax sent, for comparison): "
Response.Write Decodestr (REG)
%>

Finally the perfect view of the Ajax output special characters. The interval number and the + number are out,
"Test Test+test/"
For further verification, I added the following individual special characters that encodeuricomponent could not encode, as follows:
Copy Code code as follows:

var regcode= "Chinese characters begin:! @ # $& * (*) =:/;? + END, the middle is full of special characters. ";

The result is normal, too!
However, the general Ajax to the server data is to be applied, otherwise meaningless, in order to further verify the data is the same, I made a small change to the server side, as follows:
Copy Code code as follows:

<%
Dim reg
Reg=request ("Regcode")
test2= "Chinese characters begin:! @ # $& * (*) =:/;? + END, the middle is full of special characters. "
IF test2<>decodestr (REG) Then
Response.Write "Different"
Else
Response.Write "Same"
End IF
%>

Very excited. Client output "Same", this can be assured full application.

Summarize:

1, AJAX client double apply encodeURIComponent () to the post data encoding.
2, the server side corresponding with decodeuricomponent () dual decoding can:
<script language= "javascript" runat= "Server" >
function Decodestr (str) {
Return decodeURIComponent (decodeURIComponent (str));
}
</script>
3, when receiving responsetext, no need to reverse code. Direct: Retext=xmlhttp.responsetext;
4, the server side of this line is still indispensable: <%response.charset= "GB2312"%&gt, generally in the ASP file, there are <% @LANGUAGE = "VBSCRIPT" codepage= "936"%> this line, But this line can be removed, but can not remove <%response.charset= "GB2312"%&gt, or error.

Now start by encodeURIComponent ()/decodeuricomponent () to be able to memorize.
Attached: The following several coding methods are excerpted from the JS Manual for reference:

Escape () Method:
The specified string is encoded using the ISO Latin character set. All spaces, punctuation, special characters, and other non-ASCII characters will be converted into%XX-formatted character encodings (XX equals the encoded 16 digits of the character in the character set table). For example, spaces's corresponding encoding is%20. The Unescape method is the opposite. Characters that will not be encoded by this method: @ */+

Note: You can use Unescape () to decode an escape () encoded string. But ECMAScript v3 against using this method, the application uses decodeURI () and decodeuricomponent () to replace it.

encodeURI () Method:------Note that the latter one is the size of the i--"I" is not L, and the decodeURI below is not L.
Converts the URI string into a string in escape format using the UTF-8 encoding format. Characters that will not be encoded by this method:! @ # $& * () =:/;? + '

encodeURIComponent () Method:
Converts the URI string into a string in escape format using the UTF-8 encoding format. This method encodes more characters than encodeURI (), such as/or characters. So if a string contains several parts of the URI, this method cannot be encoded, otherwise the URL will display an error after the/character is encoded. Characters that will not be encoded by this method:! * ( )


Reference content
Therefore, for Chinese strings, you only need to use escape if you do not want to convert the string encoding format into a UTF-8 format (such as when the original page and the target page charset are consistent). If your page is GB2312 or other code, and the page that accepts the parameter is UTF-8 encoded, you should use encodeURI or encodeuricomponent.
In addition, Encodeuri/encodeuricomponent was introduced after javascript1.5, and escape was in the javascript1.0 version.

decodeURI () function
The decodeURI () function decodes the URI encoded by the encodeURI () function.
<script type= "Text/javascript" >

var test1=http://www.w3school.com.cn/my first/
document.write (encodeURI (test1) + "<br/>")
document.write (decodeURI (test1))
</script>

decodeURIComponent () function: The URI encoded by the encodeURIComponent () function can be decoded.
Unescape (): Decoding the Escape.
Author: non-Physical Life blog Traindiy
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.