Fire Station College (bkjia.com) PHP tutorialThe PHP program writes a bit of Chinese data in the cookie, while reading it in JavaScript does not display correctly? I believe many friends have encountered this situation, the day before the search, found a solution: PHP to write a cookie in UTF-8 encoding, and JS read out the time also decoded on it, because JavaScript internal use of Unicode encoding.
The following is the referenced content:
/**
*
* URL Encode/decode
*
**/
var Url = {
Public method for URL encoding
Encode:function (String) {
Return Escape (This._utf8_encode (string));
},
Public method for URL decoding
Decode:function (String) {
Return This._utf8_decode (Unescape (string));
},
Private method for UTF-8 encoding
_utf8_encode:function (String) {
String = String.Replace (/\r\n/g, "\ n");
var utftext = "";
for (var n = 0; n < string.length; n++) {
var c = string.charcodeat (n);
if (c < 128) {
Utftext + = String.fromCharCode (c);
}
else if ((C > 127) && (C < 2048)) {
Utftext + = String.fromCharCode ((c >> 6) | 192);
Utftext + = String.fromCharCode ((C & 63) | 128);
}
else {
Utftext + = String.fromCharCode ((c >> 12) | 224);
Utftext + = String.fromCharCode (((c >> 6) & 63) | 128);
Utftext + = String.fromCharCode ((C & 63) | 128);
}
}
return utftext;
},
Private method for UTF-8 decoding
_utf8_decode:function (Utftext) {
var string = "";
var i = 0;
var c = C1 = C2 = 0;
while (I < utftext.length) {
c = utftext.charcodeat (i);
if (c < 128) {
string + = String.fromCharCode (c);
i++;
}
else if ((C > 191) && (C < 224)) {
C2 = Utftext.charcodeat (i+1);
string + = String.fromCharCode (((C &) << 6) | (C2 & 63));
i + = 2;
}
else {
C2 = Utftext.charcodeat (i+1);
C3 = Utftext.charcodeat (i+2);
string + = String.fromCharCode (((C &) << 12) | ((C2 &) << 6) | (C3 & 63));
i + = 3;
}
}
return string;
}
}
/**
* This is a read cookie
*/
function GetCookie (sName)
{
var MyCookie = Document.cookie.split (";");
for (var i = 0; i < mycookie.length; i++)
{
var cookie1 = mycookie[i].split ("=");
if (cookie1[0] = = sName)
{
Return Url.decode (cookie1[1]);
}
}
return null;
}
|
http://www.bkjia.com/PHPjc/364219.html www.bkjia.com true http://www.bkjia.com/PHPjc/364219.html techarticle Fire Station College (liehuo.net) PHP tutorial PHP program in the cookie to write a bit of Chinese data, while reading with JavaScript is not displayed correctly? I believe many friends have met this feeling ...