Many of them may be distorted or unverified during the transfer process, but they cannot be used in real time. Therefore, they decided to perform a comprehensive test on their own, and the effort was not in vain, although the final result is very simple, the process is really tiring for a new AJAX student.
You are welcome to share your new experiences with us. One thought + one thought can produce at least two thoughts.
1. When GET is sent:
Method 1: Use Response. charset = "GB2312" on the ASP server to define the output code to the client.
In this case, the client does not need to perform any conversions. The following two files:
1. Client JS
Copy codeThe Code is 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); // you can add or remove
// XmlHttp. setRequestHeader ("Cache-Control", "no-cache ");
// XmlHttp. setRequestHeader ('content-type', 'application/x-www-form-urlencoded'); // do 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:
Copy codeThe Code is as follows:
<% Response. CodePage = 936%>
<% Response. charset = "GB2312"
Dim reg
Reg = Request ("regcode ")
Response. write "Mr. Wang and his friends" 'Can be output correctly.
%>
Method 2: Use Function Conversion on the client (from the Internet ).
Copy codeThe Code is 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 specify the encoding, then AJAX is the UTF-8 by default, can not be displayed on the client, you can use this function.
Copy codeThe Code is as follows:
Retext = xmlHttp. responseText;
Retext = gb2utf8 (retext );
Alert (retext );
3. In Firefox: For details, refer to: next article
FireFox is relatively simple. It supports xmlHttp. responseText; // FireFox. But to simplify the code, we recommend that you use the preceding Code directly.
However, for general purpose, follow the methods described below in POST.
Ii. When POST is sent:
For general Chinese, the above GET method can also be used in POST, but some symbols cannot be displayed in an article on the Internet, such: in the next article, "test · test + test ·" (with an interval number in the middle) has been tested. It is true that the code is output to the client after being defined on the server side.
If,
The sender uses xmlHttp. send ("regcode =" + escape (regcode ));
Then, the server puts the received data in two encoding encodeURIComponent (escape (xxxxxxx). The result displayed is: test % 25u7A5Eest % 2520 test. In addition, this idea should be wrong. I don't know if this article is wrong when it is transferred online. It should be reversed on the server end after the client uses escape encoding for transmission. Or the REQUEST itself has the function of decoding. No second or third encoding is required. Besides, escape and encodeURIComponent cannot encode special characters.
I made the following output on the server:
Copy codeThe Code is as follows:
Test2 = "test · test + test · feedback :"
Response. write test2 & "is a special symbol" · "that is directly output by the server rather than received by the server. The following is the received data (the content is the same as that sent by the original AJAX for comparison ):"
That is to say, a special character is generated directly on the server. The server file has been encoded as GB2312 using <% Response. charset = "GB2312" %>. However, the output result is that the test2 = "test · test + test · feedback generated on the server side:" The output can be normal, but the received AJAX value will not work.
Even if you try to use the three JS encoding parameters escape () \ encodeURI () \ encodeURIComponent () on the client, and then output the code at the server provider. This indicates that the special characters in the string have been deformed when the server receives them.
Now the problem is defined in encoding transfer. To illustrate this problem, I made another small experiment: assign this string to a variable in ASP and then assign it to JS using the ASP variable, as follows:
Copy codeThe Code is as follows:
<%
Para = "test · test + test ·/"
Para = Server. urlencode (para)
%>
Then hand over the JS variable, as shown below:
Copy codeThe Code is 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 ASP server. urlencode can fully encode special characters. JS is still lacking.
What should we do now?
If there is no way, I think that encodeURIComponent () can be more special character encoding than encode (). Then, like multiple MD5 encryption, it may be better to increase the hardening agent, so I applied two encodeURIComponent (), and the current code is:
Copy codeThe Code is as follows:
Var regcode = "test · test + test ·/";
XmlHttp. setRequestHeader ('content-type', 'application/x-www-form-urlencoded; charset = gb2312 ');
XmlHttp. send ("regcode =" + encodeURIComponent (regcode )));
The above is the client, and then change the server:
Copy codeThe Code is as follows:
<Script language = "javascript" runat = "server">
Function decodestr (str ){
Return decodeURIComponent (str ));
}
</Script>
<%
Dim reg
Reg = Request ("regcode ")
Test2 = "test · test + test · feedback :"
Response. write test2 & "is a special symbol" · "that is directly input by the service rather than received by the Service. The following is the received data (the content is the same as that sent by the original AJAX for comparison ):"
Response. write decodestr (reg)
%>
Finally, we can see the special characters output by AJAX. Both the interval number and the "+" number are displayed,
"Test · test + test ·/"
For further verification, I added the following special characters that encodeURIComponent cannot encode, as shown below:
Copy codeThe Code is as follows:
Var regcode = "starting with a Chinese character :! @ # $ & * (·) = :/;? + Ends with special characters in the middle. ";
The results are also normal, great!
However, the data transmitted by AJAX to the server is usually applied, otherwise it does not make sense. To further verify whether the data is the same, I made a small modification on the server side, as shown below:
Copy codeThe Code is as follows:
<%
Dim reg
Reg = Request ("regcode ")
Test2 = "starting with a Chinese character :! @ # $ & * (·) = :/;? + Ends with special characters in the middle. "
IF test2 <> decodestr (reg) Then
Response. write "different"
Else
Response. write "same"
End IF
%>
Very excited. The client output is "the same", so you can safely apply it in all aspects.
Summary:
1. the AJAX client uses encodeURIComponent () to encode the POST data.
2. Use decodeURIComponent () to decode the server:
<Script language = "javascript" runat = "server">
Function decodestr (str ){
Return decodeURIComponent (str ));
}
</Script>
3. When receiving responseText, no anti-encoding is required. Direct: retext = xmlHttp. responseText;
4. This line on the server is still indispensable: <% Response. charset = "GB2312" %>, usually in ASP files, there are <% @ LANGUAGE = "VBSCRIPT" CODEPAGE = "936" %> lines, but this line can be removed, <% Response. charset = "GB2312" %>. Otherwise, an error occurs.
Now, you can memorize encodeURIComponent ()/decodeURIComponent.
Appendix: The following encoding methods are taken from the JS manual for your reference:
Escape () method:
The specified string is encoded using the ISO Latin character set. All space characters, punctuation marks, special characters, and other non-ASCII characters will be converted into character encoding in % xx format (xx equals to the hexadecimal encoding of this character in the character set table number ). For example, the space character is encoded as % 20. The unescape method is the opposite. Characters not encoded by this method: @ */+
Note: You can use unescape () to decode the escape () encoded string. However, ECMAScript v3 opposed this method. The application uses decodeURI () and decodeURIComponent () to replace it.
EncodeURI () method: ------ note that the next one is the size I -- "I" is not L, and the following decodeURI is not L.
Convert a URI string to an escape string in UTF-8 encoding format. Characters not encoded by this method :! @ # $ & * () = :/;? +'
EncodeURIComponent () method:
Convert a URI string to an escape string in UTF-8 encoding format. Compared with encodeURI (), this method will encode more characters, such. Therefore, if the string contains several parts of the URI, this method cannot be used for encoding. Otherwise, the URL will display an error after the/character is encoded. Characters not encoded by this method :! *()
Reference content
Therefore, for a Chinese string, if you do not want to convert the string encoding format to the UTF-8 format (for example, when the charset of the original page and the target page is consistent), you only need to use escape. If your page is GB2312 or another code, and the page that accepts the parameter is UTF-8 code, use encodeURI or encodeURIComponent.
In addition, encodeURI/encodeURIComponent is introduced after javascript1.5, and escape is available in javascript1.0.
DecodeURI () function
The decodeURI () function can decode 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: decodes the URI encoded by the encodeURIComponent () function.
Unescape (): Decode escape.
Author: non-physical life blog traindiy