如何使用jQuery操作Cookies方法解析

Viola ·
更新时间:2024-09-20
· 561 次阅读

Cookies

  定义:让网站服务器把少量数据储存到客户端的硬盘或内存,从客户端的硬盘读取数据的一种技术;

  下载与引入:jquery.cookie.js基于jquery;先引入jquery,再引入:jquery.cookie.js;下载:http://plugins.jquery.com/cookie/

<script type="text/javascript" src="js/jquery.min.js">
</script><script type="text/javascript" src="js/jquery.cookie.js"></script>

  jquery.cookie.js代码的内容并不多,可以直接拷贝一下

jQuery.cookie = function (key, value, options) { // key and value given, set cookie... if (arguments.length > 1 && (value === null || typeof value !== "object")) { options = jQuery.extend({}, options); if (value === null) { options.expires = -1; } if (typeof options.expires === 'number') { var days = options.expires, t = options.expires = new Date(); t.setDate(t.getDate() + days); } return (document.cookie = [ encodeURIComponent(key), '=', options.raw ? String(value) : encodeURIComponent(String(value)), options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE options.path ? '; path=' + options.path : '', options.domain ? '; domain=' + options.domain : '', options.secure ? '; secure' : '' ].join('')); } // key and possibly options given, get cookie... options = value || {}; var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent; return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null; };

1.添加一个"会话cookie"

$.cookie('the_cookie', 'the_value');

  这里没有指明 cookie有效时间,所创建的cookie有效期默认到用户关闭浏览器为止,所以被称为 “会话cookie(session cookie)”。

2.创建一个cookie并设置有效时间为 7天

$.cookie('the_cookie', 'the_value', { expires: 7 });

  这里指明了cookie有效时间,所创建的cookie被称为“持久 cookie (persistent cookie)”。注意单位是:天;

  PS:这里好像是有问题啊,试了半天,发现jquery设置的cookie过期时间关闭浏览器就失效,https://www.cnblogs.com/acm-bingzi/p/jquery_cookie_expire.html

3.创建一个cookie并设置 cookie的有效路径

$.cookie('the_cookie', 'the_value', { expires: 7, path: '/' });

  在默认情况下,只有设置 cookie的网页才能读取该 cookie。如果想让一个页面读取另一个页面设置的cookie,必须设置cookie的路径。cookie的路径用于设置能够读取 cookie的顶级目录。将这个路径设置为网站的根目录,可以让所有网页都能互相读取 cookie (一般不要这样设置,防止出现冲突)。

4.读取cookie

$.cookie('the_cookie');

5.删除cookie

$.cookie('the_cookie', null); //通过传递null作为cookie的值即可

6.可选参数

$.cookie('the_cookie','the_value',{
  expires:7,
  path:'/',
  domain:'jquery.com',
  secure:true
}) 

expires:(Number|Date)有效期;设置一个整数时,单位是天;也可以设置一个日期对象作为Cookie的过期日期; path:(String)创建该Cookie的页面路径; domain:(String)创建该Cookie的页面域名; secure:(Booblean)如果设为true,那么此Cookie的传输会要求一个安全协议,例如:HTTPS;



cookies jQuery

需要 登录 后方可回复, 如果你还没有账号请 注册新账号