1.纯js代码操作:
//添加cookie
//name=cookie名称
//value=cookie值
//expiresHours=过期时间
//document.cookie = "name=value;domain=.google.com";
//这样,所有google.com下的主机都可以访问该cookie。
//例如:www.google.com和gmail.google.com就是两个不同的主机名。
function addCookie(name, value, expiresHours,path) {
var cookieString = name + "=" + escape(value);
//判断是否设置过期时间
if (expiresHours > 0) {
var date = new Date();
date.setTime(date.getTime + expiresHours * 3600 * 1000);
cookieString = cookieString + "; expires=" + date.toGMTString();
}
if (path != null) {
cookieString += ";path=/"+path;
}
document.cookie = cookieString;
}
//获取cookie
//name=cookie名称
//使用unescape解码
function getCookie(name) {
var strCookie = document.cookie;
var arrCookie = strCookie.split("; ");
for (var i = 0; i < arrCookie.length; i++) {
var arr = arrCookie[i].split("=");
if (arr[0] == name) return arr[1];
}
return "";
}
//删除cookie
//name=cookie名称
function deleteCookie(name) {
var date = new Date();
date.setTime(date.getTime() - 10000);
document.cookie = name + "=v; expires=" + date.toGMTString();
}
使用方法:
//添加cookie
addCookie('easyuiThemeName', 'lgl', 2,'/');
//删除cookie
deleteCookie('easyuiThemeName');
//字符串解码
alert(unescape(getCookie('easyuiThemeName')));
2.jquery.cookie
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;
};
调用方法:
//添加cookie name value 过期时间 访问cookie的目录
$.cookie('easyuiThemeName', "lgl 2015/9/16 17:14", { expires: 2,path:'/' });
//获取cookie 根据name
$.cookie('easyuiThemeName')
//删除cookie
$.cookie('easyuiThemeName',null,{ expires: -1 });
注:在默认情况下,只有设置 cookie的网页才能读取该 cookie。如果想让一个页面读取另一个页面设
置的cookie,必须设置cookie的路径。cookie的路径用于设置能够读取 cookie的顶级目录。将这
个路径设置为网站的根目录,可以让所有网页都能互相读取 cookie (一般不要这样设置,防止出现冲突) 。
3.服务端同样可以读取到该cookie:
protected void Page_Load(object sender, EventArgs e)
{
string data = Request.Cookies["easyuiThemeName"].Value;
Response.Write("<script>alert(unescape('" + data + "'));</script>");
}