开发者

Garbled characters in cookie

I store Chinese characters in cookie but the cookie value changes to garbled characters. What should I do?

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 corrup开发者_JAVA技巧ted


Try this, works for me.

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)); 


You'll just have to encode the value (and maybe the name if that can contain Chinese characters too) before setting the cookie (I'm not sure what encoding decodeURI is using, but presumably, whatever encoding that it, it has an encode verb to match the decode one, y?-)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜