When passing a Chinese string through AJAX, the Chinese string must be encoded as unicode. Generally, the built-in function escape () of JS is used (). however, a better function is found to determine the function for converting Chinese characters to unicode encoding.
The Code is as follows:
Function uniencode (text)
{
Text = escape (text. toString (). replace (/\ +/g, "% 2B ");
Var matches = text. match (/(% ([0-9A-F] {2})/gi );
If (matches)
{
For (var matchid = 0; matchid <matches. length; matchid ++)
{
Var code = matches [matchid]. substring (1, 3 );
If (parseInt (code, 16) >= 128)
{
Text = text. replace (matches [matchid], '% u00' + code );
}
}
}
Text = text. replace ('% 25',' % u0025 ');
Return text;
}
Of course, the server needs to perform the second Transcoding of the encoded string. Convert the string into UTF-8 encoding.
The Code is as follows:
Function convert_int_to_utf8 ($ intval)
{
$ Intval = intval ($ intval );
Switch ($ intval)
{
// 1 byte, 7 bits
Case 0:
Return chr (0 );
Case ($ intval & 0x7F ):
Return chr ($ intval );
// 2 bytes, 11 bits
Case ($ intval & 0x7FF ):
Return chr (0xC0 | ($ intval> 6) & 0x1F )).
Chr (0x80 | ($ intval & 0x3F ));
// 3 bytes, 16 bits
Case ($ intval & 0 xFFFF ):
Return chr (0xE0 | ($ intval> 12) & 0x0F )).
Chr (0x80 | ($ intval> 6) & 0x3F )).
Chr (0x80 | ($ intval & 0x3F ));
// 4 bytes, 21 bits
Case ($ intval & 0x1FFFFF ):
Return chr (0xF0 | ($ intval> 18 )).
Chr (0x80 | ($ intval> 12) & 0x3F )).
Chr (0x80 | ($ intval> 6) & 0x3F )).
Chr (0x80 | ($ intval & 0x3F ));
}
}
In this way, Chinese strings can be converted into UTF-8 encoding. This method is suitable for various server environments ..