Js操作Cookie封装的代码[各个浏览器测试兼容]:
操作Cookie封装方法(函数)
1
function
SetCookie(name, value)
//
两个参数,一个是cookie的名子,一个是值
2 {
3 var Days = 1 ; // 此 cookie 将被保存 30 天
4 var exp = new Date(); // new Date("December 31, 9998");
5 exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000 );
6 document.cookie = name + " = " + escape(value) + " ;expires= " + exp.toGMTString();
7 }
8 function getCookie(name) // 读取cookies函数
9 {
10 var arr = document.cookie.match( new RegExp( " (^| ) " + name + " =([^;]*)(;|$) " ));
11 if (arr != null ) return unescape(arr[ 2 ]); return null ;
12
13 }
14 function delCookie(name) // 删除cookie
15 {
16 var exp = new Date();
17 exp.setTime(exp.getTime() - 1 );
18 var cval = getCookie(name);
19 if (cval != null ) document.cookie = name + " = " + cval + " ;expires= " + exp.toGMTString();
20 }
2 {
3 var Days = 1 ; // 此 cookie 将被保存 30 天
4 var exp = new Date(); // new Date("December 31, 9998");
5 exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000 );
6 document.cookie = name + " = " + escape(value) + " ;expires= " + exp.toGMTString();
7 }
8 function getCookie(name) // 读取cookies函数
9 {
10 var arr = document.cookie.match( new RegExp( " (^| ) " + name + " =([^;]*)(;|$) " ));
11 if (arr != null ) return unescape(arr[ 2 ]); return null ;
12
13 }
14 function delCookie(name) // 删除cookie
15 {
16 var exp = new Date();
17 exp.setTime(exp.getTime() - 1 );
18 var cval = getCookie(name);
19 if (cval != null ) document.cookie = name + " = " + cval + " ;expires= " + exp.toGMTString();
20 }
asp.net生成客户端Cookie(可用上面方法getCookie()取得):
产生客户端Cookie
1
HttpCookie hk1
=
new
HttpCookie(
"
key
"
);
2 hk1.Value = " Value " ;
3 DateTime dt1 = DateTime.Now;
4 TimeSpan ts1 = new TimeSpan( 12 , 0 , 0 ); // 保存12个小时
5 hk1.Expires = dt1.Add(ts1);
6 Response.AppendCookie(hk1)
7
2 hk1.Value = " Value " ;
3 DateTime dt1 = DateTime.Now;
4 TimeSpan ts1 = new TimeSpan( 12 , 0 , 0 ); // 保存12个小时
5 hk1.Expires = dt1.Add(ts1);
6 Response.AppendCookie(hk1)
7
ps:一般简单的用法基本够用了,在这就是抛个砖,有玉经管抛过来吧!欢迎代码交流指正!
如果本文对你有所帮助,请打赏——1元就足够感动我:)
联系邮箱:intdb@qq.com
我的GitHub: https://github.com/vipstone
联系邮箱:intdb@qq.com
我的GitHub: https://github.com/vipstone
关注公众号:
作者: 王磊
出处: http://vipstone.cnblogs.com/
本文版权归作者和博客园共有,欢迎转载,请标明出处。