javascript / jquery 操作 cookie

来源:互联网 发布:mysql 小于号转义 编辑:程序博客网 时间:2024/06/06 00:58
 

什么是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 。赋值的格式:

Js代码 复制代码 收藏代码
  1. documents.cookie = 'cookieName=' + escape('cookievalue')   
  2. + ';expires=' + expirationDateObj.toGMTString();  
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 个月后过期。

Js代码 复制代码 收藏代码
  1. var expires = new Date();   
  2. expires.setTime(expires.getTime() + 3 * 30 * 24 * 60 * 60 * 1000);   
  3. /* 三个月 x 一个月当作 30 天 x 一天 24 小时  
  4. x 一小时 60 分 x 一分 60 秒 x 一秒 1000 毫秒 */  
  5. documents.cookie = 'name=rose;expires=' + expires.toGMTString();  
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 的值。

Js代码 复制代码 收藏代码
  1. function getCookie(cookieName) {   
  2. var cookieString = documents.cookie;   
  3. var start = cookieString.indexOf(cookieName + '=');   
  4. // 加上等号的原因是避免在某些 Cookie 的值里有   
  5. // 与 cookieName 一样的字符串。   
  6. if (start == -1) // 找不到   
  7. return null;   
  8. start += cookieName.length + 1;   
  9. var end = cookieString.indexOf(';', start);   
  10. if (end == -1) return unescape(cookieString.substring(start));   
  11. return unescape(cookieString.substring(start, end));   
  12. }  
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 。

Js代码 复制代码 收藏代码
  1. var expires = new Date();   
  2. expires.setTime(expires.getTime() - 1);   
  3. documents.cookie = 'name=rose;expires=' + expires.toGMTString();  
var expires = new Date();expires.setTime(expires.getTime() - 1);documents.cookie = 'name=rose;expires=' + expires.toGMTString();

 

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

 

实例:

 

Html代码 复制代码 收藏代码
  1. <html>  
  2. <head>  
  3. <script type="text/javascript">  
  4. function getCookie(c_name)   
  5. {   
  6. if (document.cookie.length>0)   
  7.   {   
  8.   c_start=document.cookie.indexOf(c_name + "=")   
  9.   if (c_start!=-1)   
  10.     {    
  11.     c_startc_start=c_start + c_name.length+1    
  12.     c_end=document.cookie.indexOf(";",c_start)   
  13.     if (c_end==-1) c_end=document.cookie.length   
  14.     return unescape(document.cookie.substring(c_start,c_end))   
  15.     }    
  16.   }   
  17. return ""   
  18. }   
  19.   
  20. function setCookie(c_name,value,expiredays)   
  21. {   
  22. var exdate=new Date()   
  23. exdate.setDate(exdate.getDate()+expiredays)   
  24. document.cookie=c_name+ "=" +escape(value)+   
  25. ((expiredays==null) ? "" : ";expires="+exdate.toGMTString())   
  26. }   
  27.   
  28. function checkCookie()   
  29. {   
  30. username=getCookie('username')   
  31. if (username!=null && username!="")   
  32.   {alert('Welcome again '+username+'!')}   
  33. else    
  34.   {   
  35.   username=prompt('Please enter your name:',"")   
  36.   if (username!=null && username!="")   
  37.     {   
  38.     setCookie('username',username,365)   
  39.     }   
  40.   }   
  41. }   
  42. </script>  
  43. </head>  
  44.   
  45. <body onLoad="checkCookie()">  
  46. </body>  
  47. </html>  
<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:

 

Js代码 复制代码 收藏代码
  1. $.cookie("blog", "css9.net");  
$.cookie("blog", "css9.net");
 

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

 

Js代码 复制代码 收藏代码
  1. $.cookie("blog", "css9.net", { expires: 7 });  
$.cookie("blog", "css9.net", { expires: 7 });
 

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

 

Js代码 复制代码 收藏代码
  1. $.cookie("blog", "css9.net", { path: '/admin', expires: 7 });  
$.cookie("blog", "css9.net", { path: '/admin', expires: 7 });
 

读取Cookie:

读取名称为blog的cookie值:

 

Js代码 复制代码 收藏代码
  1. alert( $.cookie("blog") );  
alert( $.cookie("blog") );
 

删除cookie:

 

Js代码 复制代码 收藏代码
  1. $.cookie("example", null);  
$.cookie("example", null);
 

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

 

 

代码:

 

Js代码 复制代码 收藏代码
  1. /**  
  2.  * Cookie plugin  
  3.  *  
  4.  * Copyright (c) 2006 Klaus Hartl (stilbuero.de)  
  5.  * Dual licensed under the MIT and GPL licenses:  
  6.  * http://www.opensource.org/licenses/mit-license.php  
  7.  * http://www.gnu.org/licenses/gpl.html  
  8.  *  
  9.  */  
  10.   
  11. /**  
  12.  * Create a cookie with the given name and value and other optional parameters.  
  13.  *  
  14.  * @example $.cookie('the_cookie', 'the_value');  
  15.  * @desc Set the value of a cookie.  
  16.  * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });  
  17.  * @desc Create a cookie with all available options.  
  18.  * @example $.cookie('the_cookie', 'the_value');  
  19.  * @desc Create a session cookie.  
  20.  * @example $.cookie('the_cookie', null);  
  21.  * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain  
  22.  *       used when the cookie was set.  
  23.  *  
  24.  * @param String name The name of the cookie.  
  25.  * @param String value The value of the cookie.  
  26.  * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.  
  27.  * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.  
  28.  *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.  
  29.  *                             If set to null or omitted, the cookie will be a session cookie and will not be retained  
  30.  *                             when the the browser exits.  
  31.  * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).  
  32.  * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).  
  33.  * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will  
  34.  *                        require a secure protocol (like HTTPS).  
  35.  * @type undefined  
  36.  *  
  37.  * @name $.cookie  
  38.  * @cat Plugins/Cookie  
  39.  * @author Klaus Hartl/klaus.hartl@stilbuero.de  
  40.  */  
  41.   
  42. /**  
  43.  * Get the value of a cookie with the given name.  
  44.  *  
  45.  * @example $.cookie('the_cookie');  
  46.  * @desc Get the value of a cookie.  
  47.  *  
  48.  * @param String name The name of the cookie.  
  49.  * @return The value of the cookie.  
  50.  * @type String  
  51.  *  
  52.  * @name $.cookie  
  53.  * @cat Plugins/Cookie  
  54.  * @author Klaus Hartl/klaus.hartl@stilbuero.de  
  55.  */  
  56. jQuery.cookie = function(name, value, options) {   
  57.     if (typeof value != 'undefined') { // name and value given, set cookie   
  58.         options = options || {};   
  59.         if (value === null) {   
  60.             value = '';   
  61.             options.expires = -1;   
  62.         }   
  63.         var expires = '';   
  64.         if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {   
  65.             var date;   
  66.             if (typeof options.expires == 'number') {   
  67.                 date = new Date();   
  68.                 date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));   
  69.             } else {   
  70.                 date = options.expires;   
  71.             }   
  72.             expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE   
  73.         }   
  74.         // CAUTION: Needed to parenthesize options.path and options.domain   
  75.         // in the following expressions, otherwise they evaluate to undefined   
  76.         // in the packed version for some reason...   
  77.         var path = options.path ? '; path=' + (options.path) : '';   
  78.         var domain = options.domain ? '; domain=' + (options.domain) : '';   
  79.         var secure = options.secure ? '; secure' : '';   
  80.         document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');   
  81.     } else { // only name given, get cookie   
  82.         var cookieValue = null;   
  83.         if (document.cookie && document.cookie != '') {   
  84.             var cookies = document.cookie.split(';');   
  85.             for (var i = 0; i < cookies.length; i++) {   
  86.                 var cookie = jQuery.trim(cookies[i]);   
  87.                 // Does this cookie string begin with the name we want?   
  88.                 if (cookie.substring(0, name.length + 1) == (name + '=')) {   
  89.                     cookieValue = decodeURIComponent(cookie.substring(name.length + 1));   
  90.                     break;   
  91.                 }   
  92.             }   
  93.         }   
  94.         return cookieValue;   
  95.     }   
  96. };  
原创粉丝点击