一、JavaScript
基本的cookie 操作有三种:get,set,unset;
当document.cookie用来获取属性值时, 返回当前页面可用的(根据cookie 的域、路径、失效时间和安全设置)所有cookie的字符串,一系列由分号隔开的名值对儿;
var CookieUtil = { get: function (name){ var cookieName = encodeURIComponent(name) + "=", //indexOf()返回某个指定的字符串值在字符串中首次出现的位置 cookieStart = document.cookie.indexOf(cookieName), cookieValue = null; if (cookieStart > -1){ //查找该位置之后的第一个分号(表示了该cookie 的结束位置) var cookieEnd = document.cookie.indexOf(";", cookieStart); if (cookieEnd == -1){ //没有分号,则表示是最后一个cookie cookieEnd = document.cookie.length; } cookieValue = decodeURIComponent(document.cookie.substring( cookieStart+cookieName.length, cookieEnd)); } return cookieValue; }, set: function (name, value, expires, path, domain, secure) { var cookieText = encodeURIComponent(name) + "=" + encodeURIComponent(value); if (expires instanceof Date) { cookieText += "; expires=" + expires.toGMTString(); } if (path) { cookieText += "; path=" + path; } if (domain) { cookieText += "; domain=" + domain; } if (secure) { cookieText += "; secure"; } document.cookie = cookieText; }, unset: function (name, path, domain, secure){ this.set(name, "", new Date(0), path, domain, secure); } };
二、jquery
jquery使用Cookie插件来管理Cookie;
1.写入cookie
$.cookie(‘the_cookie‘,‘the_value‘)
2.读取cookie
$.cookie(‘the_cookie‘)
3.删除cookie
$.cookie(‘the_cookie‘,null)
时间: 2024-10-20 08:59:36