您的位置:首页 > Web前端 > JavaScript

JavaScript Cookie对象

2007-12-10 11:58 316 查看
JavaScript Cookie对象

Cookie对象:

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

Cookie文件的格式:

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

写入Cookie:

格式:

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

备注:

有效日期格式:Wdy,DD-Mon-YY HH:MM:SS GMT

Wdy / Mon:英文星期 / 月份;

还包含path、domain、secure属性;

每个Web站点(domain)可建立20个Cookie数据;

每个浏览器可存储300个Cookie数据,4k字节;

客户有权禁止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>

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息