javascript / jquery 操作 cookie

本文详细介绍了Cookie的概念、用途及其基本操作方式,包括如何通过JavaScript设定、读取和删除Cookie。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

什么是Cookie?

谓Cookie,是网页 通过浏览器保 存在用户本地计算机 上的一小段数据 。用户再次访问该网页的时候,浏览器会将这一小段数据发送给该网页。Cookie是网景公司的前雇员Lou Montulli在1993年3月的发明。

 

Cookie 最典型的应用是判定注册用户是否已经登录网站。用户可能会得到提示,是否在下一次进入此网站时保留用户信息以便简化登录手续,也就是所谓“保存登录信息” 或“记住我”,这些所谓“记忆”都是用Cookie保存的。另一个重要应用场合是“购物车” 之类处理。用户可能会在一段时间内在同一家网站的不同页面中选择不同的商品,网页把这些信息会写入Cookie,以便在最后付款时提取信息。

Cookie里面都有些什么?

Cookie一般包含至少下面3项内容。

  • 具体数据的名称和值
  • 过期日
  • 针对网页的域名和路径

如果没有指定过期日,Cookie在浏览器关闭时过期;如果想Cookie永不过期,就把过期日指定为当前日期加上一万年好了(^_*)。

Cookie究竟有多大?

根据Internet标准RFC 2109, HTTP State Management Mechanism

  • 每个Cookie可以有4096字节(4KB)
  • 一个浏览器至少保存300个Cookie
  • 一个站点的Cookie数量不超过20个

当然,不同浏览器可以有自己的设置,可以放宽上面的这些限制。上面的只是最小限制。

 

 

  我们先要学一学 Cookie 的基本知识。

  每个 Cookie 都是这样的: <cookie >=< >

   <cookie > 的限制与 javascript 的命名限制大同小异,少了 不能用 javascript 关键字 ,多了 只能用可以用在 URL 编码中的字符 。后者比较难懂,但是只要你只用字母和数字命名,就完全没有问题了。 < > 的要求也是 只能用可以用在 URL 编码中的字符

  每个 Cookie 都有失效日期,一旦电脑的时钟过了失效日期,这个 Cookie 就会被删掉。我们不能直接删掉一个 Cookie ,但是可以用设定失效日期早于现在时刻的方法来间接删掉它。

  每个网页,或者说每个站点,都有它自己的 Cookies ,这些 Cookies 只能由这个站点下的网页来访问,来自其他站点或同一站点下未经授权的区域的网页,是不能访问的。每一 ”Cookies 有规定的总大小(大约 2KB ),一超过最大总大小,则最早失效的 Cookie 先被删除,来让新的 Cookie“ 安家

  现在我们来学习使用 documents.cookie 属性。

  如果直接使用 documents.cookie 属性,或者说,用某种方法,例如给变量赋值,来获得 documents.cookie 的值,我们就可以知道在现在的文档中有多少个 Cookies ,每个 Cookies 的名字,和它的值。例如,在某文档中添加 “document.write(documents.cookie)” ,结果显示:

name=kevin; email=kevin@kevin.com; lastvisited=index.html

这意味着,文档包含 3 Cookies name, email lastvisited ,它们的值分别是 kevin, kevin@kevin.com index.html 。可以看到,两个 Cookies 之间是用分号和空格隔开的,于是我们可以用 cookieString.split('; ') 方法得到每个 Cookie 分开的一个数组(先用 var cookieString = documents.cookie )。

  设定一个 Cookie 的方法是对 documents.cookie 赋值。与其它情况下的赋值不同,向 documents.cookie 赋值不会删除掉原有的 Cookies ,而只会增添 Cookies 或更改原有 Cookie 。赋值的格式:

documents.cookie = 'cookieName=' + escape('cookievalue')
+ ';expires=' + expirationDateObj.toGMTString();

 

是不是看到头晕了呢? cookieName 表示 Cookie 的名称, cookievalue 表示 Cookie 的值, expirationDateObj 表示储存着失效日期的日期对象名,如果不需要指定失效日期,则不需要第二行。不指定失效日期,则浏览器默认是在关闭浏览器(也就是关闭所有窗口)之后过期。

  首先 escape() 方法:为什么一定要用?因为 Cookie 的值的要求是 只能用可以用在 URL 编码中的字符 。我们知道 “escape()” 方法是把字符串按 URL 编码方法来编码的,那我们只需要用一个 “escape()” 方法来处理输出到 Cookie 的值,用 “unescape()” 来处理从 Cookie 接收过来的值就万无一失了。而且这两个方法的最常用途就是处理 Cookies 。其实设定一个 Cookie 只是 “documents.cookie = 'cookieName=cookievalue'” 这么简单,但是为了避免在 cookievalue 中出现 URL 里不准出现的字符,还是用一个 escape() 好。


  然后 “expires” 前面的分号:注意到就行了。是分号而不是其他。


  最后 toGMTString() 方法:设定 Cookie 的时效日期都是用 GMT 格式的时间的,其它格式的时间是没有作用的。

  现在我们来实战一下。设定一个 “name=rose” Cookie ,在 3 个月后过期。

var expires = new Date();
expires.setTime(expires.getTime() + 3 * 30 * 24 * 60 * 60 * 1000);
/* 三个月 x 一个月当作 30 天 x 一天 24 小时
x 一小时 60 分 x 一分 60 秒 x 一秒 1000 毫秒 */
documents.cookie = 'name=rose;expires=' + expires.toGMTString();

 

为什么没有用 escape() 方法?这是因为我们知道 rose 是一个合法的 URL 编码字符串,也就是说, 'rose' == escape('rose') 。一般来说,如果设定 Cookie 时不用 escape() ,那获取 Cookie 时也不用 unescape()

  再来一次:编写一个函数,作用是查找指定 Cookie 的值。

function getCookie(cookieName) {
var cookieString = documents.cookie;
var start = cookieString.indexOf(cookieName + '=');
// 加上等号的原因是避免在某些 Cookie 的值里有
// 与 cookieName 一样的字符串。
if (start == -1) // 找不到
return null;
start += cookieName.length + 1;
var end = cookieString.indexOf(';', start);
if (end == -1) return unescape(cookieString.substring(start));
return unescape(cookieString.substring(start, end));
}
 

这个函数用到了字符串对象的一些方法,如果你不记得了(你是不是这般没记性啊),请快去查查。这个函数所有的 if 语句都没有带上 else ,这是因为如果条件成立,程序运行的都是 return 语句,在函数里碰上 return ,就会终止运行,所以不加 else 也没问题。该函数在找到 Cookie 时,就会返回 Cookie 的值,否则返回 “null”

  现在我们要删除刚才设定的 name=rose Cookie

var expires = new Date();
expires.setTime(expires.getTime() - 1);
documents.cookie = 'name=rose;expires=' + expires.toGMTString();

 

可以看到,只需要把失效日期改成比现在日期早一点(这里是早 1 毫秒),再用同样的方法设定 Cookie ,就可以删掉 Cookie 了。

 

实例:

 

<html>
<head>
<script type="text/javascript">
function getCookie(c_name)
{
if (document.cookie.length>0)
  {
  c_start=document.cookie.indexOf(c_name + "=")
  if (c_start!=-1)
    { 
    c_start=c_start + c_name.length+1 
    c_end=document.cookie.indexOf(";",c_start)
    if (c_end==-1) c_end=document.cookie.length
    return unescape(document.cookie.substring(c_start,c_end))
    } 
  }
return ""
}

function setCookie(c_name,value,expiredays)
{
var exdate=new Date()
exdate.setDate(exdate.getDate()+expiredays)
document.cookie=c_name+ "=" +escape(value)+
((expiredays==null) ? "" : ";expires="+exdate.toGMTString())
}

function checkCookie()
{
username=getCookie('username')
if (username!=null && username!="")
  {alert('Welcome again '+username+'!')}
else 
  {
  username=prompt('Please enter your name:',"")
  if (username!=null && username!="")
    {
    setCookie('username',username,365)
    }
  }
}
</script>
</head>

<body onLoad="checkCookie()">
</body>
</html>
 

通过JQuery插件实 现cookie操作

你可以在这款插件的主页下载到它:http://plugins.jquery.com/project/Cookie

 

这里是一个示例页面:在 线示例

 

当在页面中引用了jquery文件及该插件文件后,可进行如下操作:

 

设置cookie

设置一个名称为blog,值为css9.net的cookie:

 

$.cookie("blog", "css9.net");
 

设置一个名称为blog,值为css9.net的cookie,同时设置过期时间(expires属性)为7天:

 

$.cookie("blog", "css9.net", { expires: 7 });
 

设置一个名称为blog,值为css9.net的cookie,设置过期时间(expires属性)为7天,同时设置cookie 的path属性 为”/admin”

 

$.cookie("blog", "css9.net", { path: '/admin', expires: 7 });
 

读取Cookie:

读取名称为blog的cookie值:

 

alert( $.cookie("blog") );
 

删除cookie:

 

$.cookie("example", null);
 

我简单看了下插件脚本的内容,实现是非常简单的。为了这样一个功能,要多引用一个文件,增加一个http连接数,感觉有些不值。其实可以把这个插件 里面的功能方法提出来,合并到网站的js文件中,使用时方法是一样的。

 

 

代码:

 

/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};
 

 

 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值