asp:
<%setCookie("user_id","test")%> //传一个cookie ,名: user_id 值:test
javascript:
<script>
alert(getCookie("user_id")); //读取结果显示 null 晕!
</script>
用 firefox 查看cookie,发现浏览器存放的cookie有点不同。
cookie的名:user_id 改成了 user%5Fid
为什么名称会改变呢?我到百度搜索,找到原因:
http://bbs.chinaunix.net/thread-743431-1-1.html
原来当asp采用utf-8编码后,写入浏览器的cookie会进行 urlencode 编码。
解决办法就是在javascript里进行解码: decodeURIComponent
修改后的 javascript代码:
//设置名称为name,值为value的Cookie
function setCookie (name, value)
{
var argc = setCookie.arguments.length;
var argv = setCookie.arguments;
var path = (argc > 3) ? argv[3] : null;
var domain = (argc > 4) ? argv[4] : null;
var secure = (argc > 5) ? argv[5] : false;
document.cookie = name + "=" + value + ((path == null) ? "" : ("; path=" + path)) + ((domain == null) ? "" : ("; domain=" + domain)) + ((secure == true) ? "; secure" : "");
}
//删除名称为name的Cookie
function deletecookie (name)
{
var exp = new Date();
exp.setTime (exp.getTime() - 1);
var cval = getCookie (name);
document.cookie = name + "=" + cval + "; expires=" + exp.toGMTString();
}
//取得项名称为offset的cookie值
function getCookieVal (offset)
{
var cookie_content = decodeURIComponent(document.cookie);
var endstr = cookie_content.indexOf (";", offset);
if (endstr == -1) endstr = cookie_content.length; return unescape(cookie_content.substring(offset, endstr)); }
//取得名称为name的cookie值
function getCookie (name)
{
var arg = name + "=";
var alen = arg.length;
var cookie_content = decodeURIComponent(document.cookie);
var clen = cookie_content.length;
var i = 0;
while (i < clen)
{
var j = i + alen;
if (cookie_content.substring(i, j) == arg)
return getCookieVal (j);
i = cookie_content.indexOf(" ", i) + 1;
if (i == 0) break;
}
return null;
}