用 Javascript 操作 Cookie

摘要: Cookie 是维护客户端状态的解决方案之一,在大多数服务器端语言中都提供了对 Cookie 直接操作的函数,在客户端,我们可以用 javascript 来实现对 Cookie 的操作。本文介绍的就是用 Javascript 操作 Cookie 的方法。
归类: Javascript,
关键词: 客户端, Javascript, 会话, cookie,
收藏本页到:
Cookie 是维护客户端状态的解决方案之一,在大多数服务器端语言中都提供了对 Cookie 直接操作的函数,在客户端,我们可以用 javascript 来实现对 Cookie 的操作。本文介绍的就是用 Javascript 操作 Cookie 的方法。


Javascript:

1.

2.
// 说明:用 Javascript 操作 Cookie
3.
// 整理:http://www.CodeBit.cn
4.

5.
function getCookie( name ) {
6.
var start = document.cookie.indexOf( name + "=" );
7.
var len = start + name.length + 1;
8.
if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
9.
return null;
10.
}
11.
if ( start == -1 ) return null;
12.
var end = document.cookie.indexOf( ';', len );
13.
if ( end == -1 ) end = document.cookie.length;
14.
return unescape( document.cookie.substring( len, end ) );
15.
}
16.

17.
function setCookie( name, value, expires, path, domain, secure ) {
18.
var today = new Date();
19.
today.setTime( today.getTime() );
20.
if ( expires ) {
21.
expires = expires * 1000 * 60 * 60 * 24;
22.
}
23.
var expires_date = new Date( today.getTime() + (expires) );
24.
document.cookie = name+'='+escape( value ) +
25.
( ( expires ) ? ';expires='+expires_date.toGMTString() : '' ) + //expires.toGMTString()
26.
( ( path ) ? ';path=' + path : '' ) +
27.
( ( domain ) ? ';domain=' + domain : '' ) +
28.
( ( secure ) ? ';secure' : '' );
29.
}
30.

31.
function deleteCookie( name, path, domain ) {
32.
if ( getCookie( name ) ) document.cookie = name + '=' +
33.
( ( path ) ? ';path=' + path : '') +
34.
( ( domain ) ? ';domain=' + domain : '' ) +
35.
';expires=Thu, 01-Jan-1970 00:00:01 GMT';
36.
}
37.



三个函数中 getCookie() 是获取Cookie值, setCookie() 是设置Cookie值,deleteCookie() 是删除Cookie。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值