2

可能重复:
cookie 中允许的字符

我正在使用JSON.stringify转换对象以将其保存在 cookie 中。但是在 cookie 中保存阿拉伯语 Windows-1256 编码后,我无法恢复它。这是我所做的:

例如:

转换并保存在 cookie 中。

conv[user]   = {"user":1,"u":1,"m":3,"c":255,"comment":'السلام عليكم ورحمه الله'};
addCookie('chat_conversations', JSON.stringify(conv) , 7);

从 cookie 中恢复值:

var con  = is_cookie('chat_conversations');
conv = jQuery.parseJSON(con);

获取我的 JSON 结果:

alert(conv[1].comment);

结果

"'D3D'E 9DJCE H1-EG 'DDG H(1C'*G\n"

这是我的 cookie 的结果

chat_conversations={"1":{"user":"1","u":"1","m":3,"c":255,"comment":"'D3D'E 9DJCE H1-EG' DDG H(1C'*G\n"}}; expires=Sat, 08 Dec 2012 15:00:42 GMT; path=/; domain=127.0.0.1

How can I save an object containing Arabic in a cookie and restore it?

4

1 回答 1

2

You should sanatise strings going into a cookie using escape or encodeURIComponent (minor differences between the two, see below) and then reverse this via unescape or decodeURICompontent when retrieving the data.

// Create obj using safe chars only
conv[user] = {
    "user" : 1, // (numbers are fine as they are)
    "u" : 1,
    "m" : 3,
    "c" : 255,
    "comment" : escape('السلام عليكم ورحمه الله') // by escaping potentially unsafe chars
};
// save
addCookie('chat_conversations', JSON.stringify(conv) , 7);
// retrieve
var con  = is_cookie('chat_conversations');
conv = jQuery.parseJSON(con);

var comment = unescape(conv[1].comment); // unescape what was escaped earlier
alert(comment);
// "السلام عليكم ورحمه الله"

escape is fine because you just want to use this data in JavaScript. If you want to access the cookie server-side then I'd strongly recommend using encodeURIComponent.

If you are just using it for JavaScript, consider window.localStorage because it will cause less internet usage.

于 2012-12-01T15:29:23.230 回答