cookie是浏览器提供的一种机制,它将document 对象的cookie属性提供给JavaScript。可以由JavaScript对其进行控制,而并不是JavaScript本身的性质。cookie是存于用户硬盘的一个文件,这个文件通常对应于一个域名,当浏览器再次访问这个域名时,便使这个cookie可用。因此,cookie可以跨越一个域名下的多个网页,但不能跨越多个域名使用。
不同的浏览器对cookie的实现也不一样,但其性质是相同的。例如在Windows 2000以及Windows xp中,cookie文件存储于documents and settings\userName\cookie\文件夹下。通常的命名格式为:userName@domain.txt。
1、设置cookie
每个cookie都是一个名/值对,可以把下面这样一个字符串赋值给document.cookie:
document.cookie=”userId=828″;
如果要一次存储多个名/值对,可以使用分号加空格(; )隔开,例如:
document.cookie=”userId=828; userName=hulk”;
在cookie 的名或值中不能使用分号(;)、逗号(,)、等号(=)以及空格。在cookie的名中做到这点很容易,但要保存的值是不确定的。如何来存储这些值呢?方 法是用escape()函数进行编码,它能将一些特殊符号使用十六进制表示,例如空格将会编码为“20%”,从而可以存储于cookie值中,而且使用此 种方案还可以避免中文乱码的出现。例如:
1 |
document.cookie="str="+escape("I love ajax"); |
等同于:
1 |
document.cookie="str=I%20love%20ajax"; |
当使用escape()编码后,在取出值以后需要使用unescape()进行解码才能得到原来的cookie值。
尽管document.cookie看上去就像一个属性,可以赋不同的值。但它和一般的属性不一样,改变它的赋值并不意味着丢失原来的值,例如连续执行下面两条语句:
1 2 |
document.cookie="userId=828"; document.cookie="userName=hulk"; |
这时浏览器将维护两个cookie,分别是userId和userName,因此给document.cookie赋值更像执行类似这样的语句:
1 2 |
document.addCookie("userId=828"); document.addCookie("userName=hulk"); |
事实上,浏览器就是按照这样的方式来设置cookie的,如果要改变一个cookie的值,只需重新赋值,例如: document.cookie=”userId=929″; 这样就将名为userId的cookie值设置为了929。
2、获取cookie的值
下面介绍如何获取cookie的值。cookie的值可以由document.cookie直接获得:
var strCookie=document.cookie;
这将获得以分号隔开的多个名/值对所组成的字符串,这些名/值对包括了该域名下的所有cookie。例如:
1 2 3 4 |
document.cookie="userId=828"; document.cookie="userName=hulk"; var strCookie=document.cookie; alert(strCookie); //userId=828:userName=hulk |
从输出可知,只能够一次获取所有的cookie值,而不能指定cookie名称来获得指定的值,这正是处理cookie值最麻烦的一部分。用户必须自己分析这个字符串,来获取指定的cookie值,例如,要获取userId的值,可以这样实现:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
//获取cookie字符串 var strCookie=document.cookie; //将多cookie切割为多个名/值对 var arrCookie=strCookie.split("; "); var userId; //遍历cookie数组,处理每个cookie对 for(var i=0;i<arrCookie.length;i++){ var arr=arrCookie[i].split("="); //找到名称为userId的cookie,并返回它的值 if("userId"==arr[0]){ userId=arr[1]; break; } } alert(userId); |
用类似的方法,可以获取一个或多个cookie的值,其主要的技巧仍然是字符串和数组的相关操作。
3、给cookie设置终止日期
到现在为止,所有的cookie都是单会话cookie,即浏览器关闭后这些cookie将会丢失,事实上这些cookie仅仅是存储在内存中,而没有建立相应的硬盘文件。
在实际开发中,cookie常常需要长期保存,例如保存用户登录的状态。这可以用下面的选项来实现:
document.cookie=”userId=828; expiress=GMT_String”;
其中GMT_String是以GMT格式表示的时间字符串,这条语句就是将userId这个cookie设置为GMT_String表示的过期时间,超过这个时间,cookie将消失,不可访问。例如:如果要将cookie设置为10天后过期,可以这样实现:
1 2 3 4 5 6 7 |
//获取当前时间 var date=new Date(); var expiresDays=10; //将date设置为10天以后的时间 date.setTime(date.getTime()+expiresDays*24*3600*1000); //将userId和userName两个cookie设置为10天后过期 document.cookie="userId=828; userName=hulk; expires="+date.toGMTString(); |
4、删除cookie
为了删除一个cookie,可以将其过期时间设定为一个过去的时间,例如:
1 2 3 4 5 6 |
//获取当前时间 var date=new Date(); //将date设置为过去的时间 date.setTime(date.getTime()-10000); //将userId这个cookie删除 document.cookie="userId=828; expires="+date.toGMTString(); |
5、指定可访问cookie的路径
默认情况下,如果在某个页面创建了一个cookie,那么该页面所在目录中的其他页面也可以访问该cookie。如果这个目录下还有子目录,则在子目录中也可以访问。例如在www.veznlee.com/article/a.html中所创建的cookie,可以被www.veznlee.com/article/b.html或www.veznlee.com/article/javascript/c.html所访问,但不能被www.veznlee.com/d.html访问。
为了控制cookie可以访问的目录,需要使用path参数设置cookie,语法如下:
1 |
document.cookie="name=value; path=cookieDir"; |
其中cookieDir表示可访问cookie的目录。例如:
1 |
document.cookie="userId=320; path=/shop"; |
就表示当前cookie仅能在shop目录下使用。
如果要使cookie在整个网站下可用,可以将cookie_dir指定为根目录,例如:document.cookie=”userId=320; path=/”;
下面为大家展示一个实例,代码亲测可行:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 |
<form> <div class="form-group clearfix"> <span>手机:</span> <input class="w310 user" type="text" id="txtUserName" placeholder="请输入用户名或邮箱或手机号"/> <i class="err"></i> </div> <div class="form-group clearfix"> <span>密码:</span> <input class="w160 code" type="text" id="txtUserPass" name="code" placeholder="请输入密码"/> <a class="getcode" href="javascript:void(0);">发送动态密码</a> </div> <div class="saveaccount"> <label class="rememberme" for="chkRememberPass"> <input type="checkbox" id="chkRememberPass" name="saveinfo1"/>记住我 </label> <a class="forgetpassword" href="javascript:void(0);">忘记密码?</a> </div> <div class="form-group clearfix"> <span></span> <input class="bgblue" type="button" onclick="userLogin()" value="登录" /> <input class="bgeee" type="reset" value="重填" /> </div> </form> <script language="javascript" type="text/javascript"> function addCookie(name,value,days,path){ /**添加设置cookie**/ var name = escape(name); var value = escape(value); var expires = new Date(); expires.setTime(expires.getTime() + days * 3600000 * 24); //path=/,表示cookie能在整个网站下使用,path=/temp,表示cookie只能在temp目录下使用 path = path == "" ? "" : ";path=" + path; //GMT(Greenwich Mean Time)是格林尼治平时,现在的标准时间,协调世界时是UTC //参数days只能是数字型 var _expires = (typeof days) == "string" ? "" : ";expires=" + expires.toUTCString(); document.cookie = name + "=" + value + _expires + path; } function getCookieValue(name){ /**获取cookie的值,根据cookie的键获取值**/ //用处理字符串的方式查找到key对应value var name = escape(name); //读cookie属性,这将返回文档的所有cookie var allcookies = document.cookie; //查找名为name的cookie的开始位置 name += "="; var pos = allcookies.indexOf(name); //如果找到了具有该名字的cookie,那么提取并使用它的值 if (pos != -1){ //如果pos值为-1则说明搜索"version="失败,!= -1搜索成功 var start = pos + name.length; //cookie值开始的位置 var end = allcookies.indexOf(";",start); //从cookie值开始的位置起搜索第一个";"的位置,即cookie值结尾的位置 if (end == -1) end = allcookies.length; //如果end值为-1说明cookie列表里只有一个cookie var value = allcookies.substring(start,end); //提取cookie的值 return unescape(value); //对它解码 }else{ //搜索失败,返回空字符串 return ""; } } function deleteCookie(name,path){ /**根据cookie的键,删除cookie,其实就是设置其失效**/ var name = escape(name); var expires = new Date(0); path = path == "" ? "" : ";path=" + path; document.cookie = name + "="+ ";expires=" + expires.toUTCString() + path; } /**实现功能,保存用户的登录信息到cookie中。当登录页面被打开时,就查询cookie**/ window.onload = function(){ console.log(document.cookie); var userNameValue = getCookieValue("userName"); document.getElementById("txtUserName").value = userNameValue; var userPassValue = getCookieValue("userPass"); document.getElementById("txtUserPass").value = userPassValue; } function userLogin(){ /**用户登录,其中需要判断是否选择记住密码**/ //简单验证一下 var userName = document.getElementById("txtUserName").value; if(userName == ''){ alert("请输入用户名。"); return; } var userPass = document.getElementById("txtUserPass").value; if(userPass == ''){ alert("请输入密码。"); return; } var objChk = document.getElementById("chkRememberPass"); if(objChk.checked){ //添加cookie addCookie("userName",userName,7,"/"); addCookie("userPass",userPass,7,"/"); alert("记住了你的密码登录。"); window.location.href = "http://www.baidu.com"; }else{ alert("不记密码登录。"); window.location.href = "http://www.baidu.com"; } } </script> |
发表评论