<html>
<script>
//设置cookie
function setCookie(){
//设置cookie
document.cookie = "userId=dj";
//指定可访问cookie的路径,为了控制cookie可以访问的目录,需要使用path参数设置cookie
document.cookie = "testCookie=001;path=index";
//如果要使cookie在整个网站下可用,可以将cookie_dir指定为根目录
document.cookie = "userName=dengjie;path=/";
document.cookie="tsetUrl=url;path=/";
alert(document.cookie);
/**
指定可访问cookie的主机名
和路径类似,主机名是指同一个域下的不同主机,例如:www.google.com和gmail.google.com就是两个不同的主机名。
默认情况下,一个主机中创建的cookie在另一个主机下是不能被访问的,但可以通过domain参数来实现对其的控制,其语法格式为:
document.cookie="name=value; domain=cookieDomain";
以google为例,要实现跨主机访问,可以写为:
document.cookie="name=value;domain=.google.com";
这样,所有google.com下的主机都可以访问该cookie。
综合示例:构造通用的cookie处理函数cookie的处理过程比较复杂,并具有一定的相似性。
因此可以定义几个函数来完成cookie的通用操作,从而实现代码的复用。下面列出了常用的cookie操作及其函数实现。
*/
//获取cookie字符串
strCookie = document.cookie;
var userId = "";
//将多cookie切割为多个键/值对
var arrCookie = strCookie.split(";");
for (var i = 0;i < arrCookie.length;i++) {
var arr = arrCookie[i].split("=");
//alert("userId"+"="+arr[0].replace(/^\s+|\s+$/g,"")+";");
//去左右空格,找到名称为userId的cookie,并返回它的值
if ("userId" == arr[0].replace(/^\s+|\s+$/g,"")) {
userId = arr[1];
break;
}
}
document.getElementById('txtId1').value = userId;
alert('cookie已设置!');
}
//添加一个cookie:该函数接收3个参数:cookie名称,cookie值,以及在多少小时后过期。这里约定expiresHours为0时不设定过期时间,即当浏览器关闭时cookie自动消失。
function addCookie(name,value,expiresHours){
var cookieString=name+"="+escape(value);
//判断是否设置过期时间
if(expiresHours>0){
var date=new Date();
date.setTime(date.getTime+expiresHours*3600*1000);
cookieString=cookieString+"; expires="+date.toGMTString();
}
document.cookie=cookieString;
}
//设置为10天后过期的cookie
function setCookie10Day(){
//获取当前时间
var date=new Date();
var expiresDays=10;
//将date设置为10天以后的时间
date.setTime(date.getTime()+expiresDays*24*3600*1000);
//将userId和userName两个cookie设置为10天后过期
document.cookie="userId=dj;userName=dengjie;expires="+date.toGMTString();
}
//删除cookie:该函数可以删除指定名称的cookie
function delCookie(name){
//获取当前时间
var date=new Date();
//将date设置为过去的时间
date.setTime(date.getTime()-10000);
//将userId这个cookie删除
document.cookie=name+"=v;path=/;expires="+date.toGMTString();
alert('cookie已删除!');
}
function viewCookie(){
alert(document.cookie);
}
</script>
<body>
<INPUT TYPE="text" ID="txtId1">
<INPUT TYPE="button" ID="btnId1" VALUE="set cookie" οnclick="setCookie()">
<INPUT TYPE="button" ID="btnId2" VALUE="delete cookie" οnclick="delCookie('userId')">
<INPUT TYPE="button" ID="btnId3" VALUE="view cookie" οnclick="viewCookie()">
</body>
</html>