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

JavaScript学习之cookies

2015-12-09 13:46 671 查看

使用JavaScript操作cookies

一、什么是cookies?

  cookies是一种对客户端硬盘的数据进行存取的技术,这种技术能够让网站把少量的数据存储到客户端的硬盘,同时也能够从客户端的硬盘读取存储的数据。存储的方式表现为一个很小的文本文件,这个文件可以存储的东西很多,比如:用户名、访问时间、密码等。

二、使用cookies

1、cookies的创建

document.cookies = name+"="+value;


  cookies的创建需要给出cookies的名称和对应的cookies值,必备属性是cookies的名称name,除此之外,cookies还有四个另外的可选属性,分别是:expires属性、path属性、domain属性、secure属性。

2、给cookies命名

  name属性是用来唯一表示cookies的,cookies的name属性可以自定义。与其他属性不同,document对象的cookies属性赋值时,并不会替代原来的值,而是会创建新的cookies。

eg:

document.cookies = "user=Tom";
document.cookies = "city=nanjing";
document.cookies = "age=20";


  上面的三条语句,创建了三个cookies。创建多个cookies时可以用一条语句,中间用分号隔开即可。

  因为cookies是通过HTTP来传递的,而HTTP不允许某个非字母和数字的字符被传递,因此cookies不能包含分号等特殊字符。为了解决这个问题,可以采用对cookies的名称和值在赋值前进行编码的方法。在JavaScript中,常用的编码方法是escape(),为了在读取的时候解码,相对应的一个解码方法是unescape().例如:

document.cookies = escape("user=Tom;city=nanjing;age=20");


3、定义cookies过期时间(expires属性)
  (1)cookies是有生命周期的,为了能够让一个cookies能够在关闭浏览器后还能持续生效,就需要使用expires属性。expires需要使用格林尼治标准时间的文本字符串,格式如下:

Weekday Mon DD HH:MM:SS Time Zone YYYY


eg:

Mon Oct 22 13:22:34 PST 2012


  (2)为了更好的控制时间,通常使用JavaScript的Date对象来进行时间的设置(这里就不列举Date对象的常用方法了,之前的学习中有详细的资料)
eg:

<script language="JavaScript">
var edate = new Date();
document.cookies = escape("user=Tom;expire="+edate.setFullYear(edate.getFullYear()+1));
</script>


  以上代码,设置了过期时间为当前时间加一年。要想让一个cookies删除,通常也是使用expires属性设置为过去的某一个时间即可。例如:

<script language="JavaScript">
var edate = new Date();
document.cookies = escape("user=Tom;expire="+edate.setFullYear(edate.getFullYear()-1));
</script>


4、定义cookies的目录范围(path属性)

  和变量的作用域一样,cookies一样有着自己的作用范围。path属性能使cookies能够被服务器上指定目录下的所有网站访问。

eg:cookies能够被服务器里www目录及其子目录下的任何网页访问到:

document.cookies = "user=Tom;path=/www";


  如果cookies 能够被服务器上所有网页访问:

document.cookies = "user=Tom;path=/";


5、实现跨服务器共享(domain属性)

  domain属性能够实现跨服务器的共享。比如对于某个网站的主站www.ds5u.com是一台服务器,但是其论坛站bbs.ds5u.com又是另一个服务器,博客站blog.ds5u.com又是另一台服务器。虽然这些网站都有各自的二级域名,但是用户是同一的,需要实现cookies的共享。例如:

document.cookies = "user=Tom;domain=.ds5u.com";


  上述代码即可实现cookies在ds5u.com这个域所在的所有服务器共享。

6、使信息传输更加安全(secure属性)

  secure属性规定cookies只能在安全的Internet上连接。通常情况下,此属性是忽略的,属性的可选值是true和false。

eg:

document.cookies = "user=Tom;secure=true";


三、让cookies存储信息

  cookies 本身的使用是有限制的,在用户的计算机上,每个服务器或域只能保存最多20个cookies,而每个浏览器的cookies总数不能超过300,cookies的最大尺寸的4k,因此不能像使用变量一样,随意的创建cookies。考虑到cookies的限制,最有效的方法是将所有需要保存到cookies中的值链接为一个字串(使用分隔符分隔),然后把这个字串赋值给一个cookies。这样,只需要创建一个cookies,就能保存若干的信息了。读取时,按照分隔符的组合规则进行信息的提取和还原。

  语法:

名称1=值1&名称2=值2&...&名称n=值n


 eg:如果要保存姓名、年龄、性别、城市、邮编这五个消息,先将消息组合成一个字串:

user=Tom&age=25&sex=male&city=nanjing&zip=210000


  然后创建一个cookies,因为字串中包含非字母和数字字符,因此在赋值前先进行编码:

document.cookie = "allinfo="+escape("user=Tom&age=25&sex=male&city=nanjing&zip=210000");


四、从cookies读取信息

  创建cookies后,读取cookies信息直接访问属性即可:

document.cookie


document.cookie通常需要用unescape()方法进行解码,eg:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>JS</title>
<script language="JavaScript">
document.cookie = escape("user=Tom;city=nanjing;zip=21000");
alert("cookies的值:"+unescape(document.cookie));
</script>
</head>

<body>

</body>
</html>


  效果:


  在这里得到的值是一个用分号分隔的字符串。可以通过String对象来获得每个cookies对应的值。eg:

    *split():将字符串按照指定的分隔符分成数组。

    *substring(starting index,ending index):提取从starting index开始到ending index结束的文本。

    *indexOf(text,index):返回text参数内的第一个字符在字符串的位置。

eg:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>读取cookies</title>
</head>
<script language="JavaScript">
<!--
document.cookie = escape("username=tom;city=nanjing;zip=210000");
var allCookies = unescape(document.cookie);
var aryCookies = allCookies.split(";");
var nowvalue;
for( var i=0; i < aryCookies.length; i++ ){
nowvalue = aryCookies[i];
if( nowvalue.substring( 0, nowvalue.indexOf("=") ) == "zip" ){
document.write("cookies中保存的邮编是:"+nowvalue.substring( nowvalue.indexOf("=")+1, nowvalue.length));
alert("cookies中保存的邮编是:"+nowvalue.substring( nowvalue.indexOf("=")+1, nowvalue.length));
break;
}
}
//-->
</script>

<body>
</body>
</html>


  效果:

(只能在IE中显示)

五、实践

eg:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>JS</title>
<script language="JavaScript">
function getCookie(c_name) {
if (document.cookie.length>0) {
c_start=document.cookie.indexOf(c_name + "=")
if (c_start!=-1) {
c_start=c_start + c_name.length+1
c_end=document.cookie.indexOf(";",c_start)
if (c_end==-1) c_end=document.cookie.length
return unescape(document.cookie.substring(c_start,c_end))
}
}
return ""
}

function setCookie(c_name,value,expiredays) {
var exdate=new Date()
exdate.setDate(exdate.getDate()+expiredays)
document.cookie=c_name+ "=" +escape(value)+
((expiredays==null) ? "" : "; expires="+exdate.toGMTString())
}

function checkCookie() {
username=getCookie('username')
if (username!=null && username!="") {
alert('Welcome again '+username+'!')}
else {
username=prompt('Please enter your name:',"")
if (username!=null && username!="") {
setCookie('username',username,365)
}
}
}
</script>
</head>

<body onLoad="checkCookie()">

</body>
</html>


效果:


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