JavaScript Cookie对象

JavaScript Cookie对象
  • Cookie对象:

是一种以文件(Cookie文件)的形式保存在客户端硬盘的Cookies文件夹中的用户数据信息(Cookie数据)。Cookie文件由所访问的 Web站点建立,以长久的保存客户端与Web站点间的会话数据,并且该Cookie数据只允许被所访问的Web站点进行读取。

  • Cookie文件的格式:

NS:Cookie.txt
IE:用户名@域名.txt

  • 写入Cookie:

格式:

document.cookie = " 关键字 = 值 [ ; expires = 有效日期 ] [;...]"

备注:

  1. 有效日期格式:Wdy,DD-Mon-YY HH:MM:SS GMT
  2. Wdy / Mon:英文星期 / 月份;
  3. 还包含path、domain、secure属性;
  4. 每个Web站点(domain)可建立20个Cookie数据;
  5. 每个浏览器可存储300个Cookie数据,4k字节;
  6. 客户有权禁止Cookie数据的写入。

例1:

<Script>

var today = new Date();
var expireDay = new Date();
var msPerMonth = 24*60*60*1000*31;
expireDay.setTime( today.getTime() + msPerMonth );

document.cookie = "name=Hubert;expires=" + expireDay.toGMTString();
document.write("已经将 Cookie 写入你的硬盘中了!<br>");
document.write("内容是:", document.cookie, "<br>");
document.write("这个 Cookie 的有效时间是:");
document.write(expireDay.toGMTString());

</Script>

例2:

<Script>

var today = new Date();
var expireDay = new Date();
var msPerMonth = 24*60*60*1000*31;
expireDay.setTime( today.getTime() + msPerMonth );

function setCookie(Key,value) {
document.cookie = Key + "=" + value + ";expires=" + expireDay.toGMTString();
}

setCookie("NAME","HUBERT");
document.write("累计的 Cookies 如下:<BR>");
document.write(document.cookie);

</Script>

 

  • 读取Cookie:

格式:

document.cookie

<Script>

function getCookie(Key){
var search = Key + "=";
begin = document.cookie.indexOf(search);
if (begin != -1) {
    begin += search.length;
    end = document.cookie.indexOf(";",begin);
    if (end == -1) end = document.cookie.length;
    return document.cookie.substring(begin,end);
}
}

document.write("嗨! ",getCookie("name"), " 欢迎光临..")

</Script>

 

  • 删除Cookie:

格式:

document.cookie = " 关键字 = ; expires = 当前日期"

例:

<Script>

var today = new Date();

function delCookie(Key) {
document.cookie = Key + "=;expires=today.toGMTString";
}

document.write("现有的 Cookies 如下:<BR>");
document.write(document.cookie, "<BR>");
delCookie("name");
document.write("删除后的 Cookies 如下:<BR>");
document.write(document.cookie);

</Script>

 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值