views:

95

answers:

2

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 corrupted
A: 

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

Alex Martelli
+1  A: 

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));
o.k.w