javascript操作cookie

<!--
//学习一下如何利用js来操作cookie

//写入 cookie
//不区分 cookieName 的大小写
//不考虑子键
function WriteCookies(cookieName, cookieValue, expires)
{
    if (expires)
    {
        //指定了 expires
        document.cookie = 
            WriteCookies_GetCookieName(cookieName) + "=" + escape(cookieValue) 
            + "; expires=" + xpires.toGMTString();
    }
    else
    {
        document.cookie = WriteCookies_GetCookieName(cookieName) + "=" + escape(cookieValue);
    }
}

//获取并返回与 cookieName 同名的 cookie 名称,允许大小写不同
//如果不存在这样的 cookie,就返回 cookieName
function WriteCookies_GetCookieName(cookieName)
{
    var lowerCookieName = cookieName.toLowerCase();
    var cookieStr = document.cookie;
   
    if (cookieStr == "")
    {
        return cookieName;
    }
   
    var cookieArr = cookieStr.split("; ");
    var pos = -1;
    for (var i=0; i<cookieArr.length; i++)
    {
        pos = cookieArr[i].indexOf("=");
        if (pos > 0)
        {
            if (cookieArr[i].substring(0, pos).toLowerCase() == lowerCookieName)
            {
                return cookieArr[i].substring(0, pos);
            }
        }
    }
   
    return cookieName;
}

//获取并返回 cookie 值
//不区分 cookieName 的大小写
//dfltValue 为默认返回值
//不考虑子键
function ReadCookies(cookieName, dfltValue)
{
    var lowerCookieName = cookieName.toLowerCase();
    var cookieStr = document.cookie;
   
    if (cookieStr == "")
    {
        return dfltValue;
    }
   
    var cookieArr = cookieStr.split("; ");
    var pos = -1;
    for (var i=0; i<cookieArr.length; i++)
    {
        pos = cookieArr[i].indexOf("=");
        if (pos > 0)
        {
            if (cookieArr[i].substring(0, pos).toLowerCase() == lowerCookieName)
            {
                return unescape(cookieArr[i].substring(pos+1, cookieArr[i].length));
            }
        }
    }
   
    return dfltValue;
}


//test all the oper

document.write("写入名称为 cv 的 cookie...<br>");
WriteCookies("test", "test123", null);

document.write("写入名称为 Ab,带失效日期的 cookie...<br>");
var expires = new Date("December 11, 2010");
WriteCookies("singleblue", "test234", expires);

document.write("读取名称为 singleblue 的 cookie..." + ReadCookies("ab", ""));
-->

posted @ 2008-06-11 10:25  singleblue  阅读(1426)  评论(2编辑  收藏  举报