开发者

Garbled characters in cookie

开发者 https://www.devze.com 2022-12-09 18:03 出处:网络
I store Chinese characters in cookie but the cookie value changes to garbled characters. What should I do?

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

精彩评论

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

关注公众号