標籤:
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;
}
asp(utf-8) set cookie 用 javascript 讀cookie發現一個問題