使用Javascript设置Cookie并清理值 [英] Set Cookie with Javascript and sanitize value

查看:75
本文介绍了使用Javascript设置Cookie并清理值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用以下命令通过javascript设置cookie:

I need to set a cookie with javascript which I'm doing this with the following command:

document.cookie = name+"="+value;

我的问题是 value 是一个字符串,可以包含任何Unicode字符。

My problem is that value is a string, which can contain any unicode-character.

是否有一个自动替换特殊字符的功能(例如; ) -并且如果不是,则禁止使用哪些字符?

Is there a function which automatically replaces special characters (like ;) - and if not, which characters are forbidden?

类似于 encodeURIComponent()的Get-Parameters函数将是完美的

Something like the "encodeURIComponent()"-Function for Get-Parameters would be perfect

推荐答案

您应使用 window.escape


scape()方法转换特殊字符(不是常规文本或数字的任何字符)转换为十六进制字符,这对于设置cookie的值尤其必要。在GET请求或AJAX GET / POST请求的URL中传递name = value对时,也很有用。

The escape() method converts special characters (any characters that are not regular text or numbers) into hexadecimal characters, which is especially necessary for setting the values of cookies. Also useful when passing name=value pairs in the URL of a GET request, or an AJAX GET/POST request.

window.unescape

更新。
使用 base64 进行编码/解码,以免Unicode字符支出少于$$ c c> window.encode 。

Upd. It may make some sense to use base64 encoding/decoding prior to escaping in order not to suffer that much from unicode characters expenditure by window.encode.

这篇关于使用Javascript设置Cookie并清理值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆