我将中文字符存储在cookie中,但cookie值变为乱码。我该怎么办?
function createCookie(name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 1000 * 60 * 60 * 24));
var expires = "; expires=" + date.toGMTString();
}
else var expires = "";
document.cookie = name + "=" + value + expires + "; path=/";
}
createCookie("city", decodeURI('%e6%b8%a9%e5%b7%9e%e5%b8%82'));
alert(decodeURI('%e6%b8%a9%e5%b7%9e%e5%b8%82')); // The Chinese characters are correct
alert(document.cookie); //The Chinese characters are corrupted
答案 0 :(得分:1)
试试这个,对我有用。
createCookie("city", '%e6%b8%a9%e5%b7%9e%e5%b8%82'); //do not decode chinese characters
alert(decodeURI('%e6%b8%a9%e5%b7%9e%e5%b8%82'));
alert(decodeURI(document.cookie));
答案 1 :(得分:0)
在设置cookie之前,您只需要对值(也可能是名称,如果它也可以包含中文字符)进行编码(我不确定编码decodeURI
正在使用什么,但可能是编码,无论编码它,它有一个匹配解码的编码动词,y? - )