cookie的应用

cookie,可以达到真正全局变量的要求

应用场景:

(1)保存用户登录状态。例如将用户id存储于一个cookie内,这样当用户下次访问该页面时就不需要重新登录了,现在很多论坛和社区都提供这样的功能。 cookie还可以设置过期时间,当超过时间期限后,cookie就会自动消失。因此,系统往往可以提示用户保持登录状态的时间:常见选项有一个月、三个 月、一年等。 

(2)跟踪用户行为。例如一个天气预报网站,能够根据用户选择的地区显示当地的天气情况。如果每次都需要选择所在地是烦琐的,当利用了 cookie后就会显得很人性化了,系统能够记住上一次访问的地区,当下次再打开该页面时,它就会自动显示上次用户所在地区的天气情况。因为一切都是在后 台完成,所以这样的页面就像为某个用户所定制的一样,使用起来非常方便。 

(3)定制页面。如果网站提供了换肤或更换布局的功能,那么可以使用cookie来记录用户的选项,例如:背景色、分辨率等。当用户下次访问时,仍然可以保存上一次访问的界面风格。 

(4)创建购物车。正如在前面的例子中使用cookie来记录用户需要购买的商品一样,在结账的时候可以统一提交。例如淘宝网就使用cookie记录了用户曾经浏览过的商品,方便随时进行比较。

(5)项目中有多种肤色或者多种语言切换的时候,或者项目列表页面复选框选择的时候,保存每页所选值得情况,导出的时候能导出每页选择的值。

cookie的缺点主要集中于安全性和隐私保护。主要包括以下几种:

(1)cookie可能被禁用。当用户非常注重个人隐私保护时,他很可能禁用浏览器的cookie功能; 
(2)cookie是与浏览器相关的。这意味着即使访问的是同一个页面,不同浏览器之间所保存的cookie也是不能互相访问的; 
(3)cookie可能被删除。因为每个cookie都是硬盘上的一个文件,因此很有可能被用户删除; 
(4)cookie安全性不够高。所有的cookie都是以纯文本的形式记录于文件中,因此如果要保存用户名密码等信息时,最好事先经过加密处理。 

设置cookie:

每个cookie都是一个名/值对,可以把下面这样一个字符串赋值给document.cookie: 
document.cookie="userId=828"; 
如果要一次存储多个名/值对,可以使用分号加空格(; )隔开,例如: 
document.cookie="userId=828; userName=hulk"; 
在cookie的名或值中不能使用分号(;)、逗号(,)、等号(=)以及空格。在cookie的名中做 

到这点很容易,但要保存的值是不确定的。如何来存储这些值呢?方法是用escape()函数进行编码,它能将一些特殊符号使用十六进制表示,例如空格将会编码为“20%”,从而可以存储于 cookie值中,而且使用此种方案还可以避免中文乱码的出现。例如: 
document.cookie="str="+escape("I love ajax"); 
相当于: 
document.cookie="str=I%20love%20ajax"; 
当使用escape()编码后,在取出值以后需要使用unescape()进行解码才能得到原来的cookie值。 

尽管document.cookie看上去就像一个属性,可以赋不同的值。但它和一般的属性不一样,改变它的赋值并不意味着丢失原来的值,例如连续执行下面两条语句: 
document.cookie="userId=828"; 
document.cookie="userName=hulk"; 
这时浏览器将维护两个cookie,分别是userId和userName,因此给document.cookie赋值更像执行类似这样的语句: 
document.addCookie("userId=828"); 
document.addCookie("userName=hulk"); 
事实上,浏览器就是按照这样的方式来设置cookie的,如果要改变一个cookie的值,只需重新赋值,例如: 
document.cookie="userId=929"; 
这样就将名为userId的cookie值设置为了929。 

获取cookie的值 
下面介绍如何获取cookie的值。cookie的值可以由document.cookie直接获得: 
var strCookie=document.cookie; 
这将获得以分号隔开的多个名/值对所组成的字符串,这些名/值对包括了该域名下的所有cookie 
<script language="JavaScript" type="text/javascript"> 
<!-- 
document.cookie="userId=828"; 
document.cookie="userName=hulk"; 
var strCookie=document.cookie; 
alert(strCookie); 
//--> 
</script> 

名称来获得指定的值,这正是处理cookie值最麻烦的一部分。用户必须自己分析这个字符串,来获取指定的cookie值,例如,要获取userId的值,可以这样实现: 
<script language="JavaScript" type="text/javascript"> 
<!-- 
//设置两个cookie 
document.cookie="userId=828"; 
document.cookie="userName=hulk"; 
//获取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); 
//--> 
</script> 


用类似的方法,可以获取一个或多个cookie的值,其主要的技巧仍然是字符串和数组的相关操作. 

给cookie设置终止日期  
到现在为止,所有的cookie都是单会话cookie,即浏览器关闭后这些cookie将会丢失,事实上这些cookie仅仅是存储在内存中,而没有建立相应的硬盘文件。 
在实际开发中,cookie常常需要长期保存,例如保存用户登录的状态。这可以用下面的选项来实现: 
document.cookie="userId=828; expires=GMT_String"; 
其中GMT_String是以GMT格式表示的时间字符串,这条语句就是将userId这个cookie设置为 

GMT_String表示的过期时间,超过这个时间,cookie将消失,不可访问。例如:如果要将cookie 

设置为10天后过期,可以这样实现: 
<script language="JavaScript" type="text/javascript"> 
<!-- 
//获取当前时间 
var date=new Date(); 
var expireDays=10; 
//将date设置为10天以后的时间 
date.setTime(date.getTime()+expireDays*24*3600*1000); 
//将userId和userName两个cookie设置为10天后过期 
document.cookie="userId=828; userName=hulk; expire="+date.toGMTString(); 
//--> 
</script> 

删除cookie  
为了删除一个cookie,可以将其过期时间设定为一个过去的时间,例如:   
<script language="JavaScript" type="text/javascript"> 
<!-- 
//获取当前时间 
var date=new Date(); 
//将date设置为过去的时间 
date.setTime(date.getTime()-10000); 
//将userId这个cookie删除 
document.cookie="userId=828; expire="+date.toGMTString(); 
//--> 
</script>

指定可访问cookie的路径  
默认情况下,如果在某个页面创建了一个cookie,那么该页面所在目录中的其他页面也可以访问该cookie。如果这个目录下还有子目录,则在子目录中也可以访问。例如在 

www.xxxx.com/html/a.html中所创建的cookie,可以被www.xxxx.com/html/b.html或 

www.xxx.com/ html/ some/c.html所访问,但不能被www.xxxx.com/d.html访问。 
为了控制cookie可以访问的目录,需要使用path参数设置cookie,语法如下: 
document.cookie="name=value; path=cookieDir"; 
其中cookieDir表示可访问cookie的目录。例如: 
document.cookie="userId=320; path=/shop"; 
就表示当前cookie仅能在shop目录下使用。 
如果要使cookie在整个网站下可用,可以将cookie_dir指定为根目录,例如: 
document.cookie="userId=320; path=/"; 


指定可访问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操作及其函数实现。 
1.添加一个cookie:addCookie(name,value,expireHours) 
该函数接收3个参数:cookie名称,cookie值,以及在多少小时后过期。这里约定expireHours为0时不设定过期时间,即当浏览器关闭时cookie自动消失。该函数实现如下: 
<script language="JavaScript" type="text/javascript"> 
<!-- 
function addCookie(name,value,expireHours){ 
         var cookieString=name+"="+escape(value); 
         //判断是否设置过期时间 


         if(expireHours>0){ 
                var date=new Date(); 
                date.setTime(date.getTime+expireHours*3600*1000); 
                cookieString=cookieString+"; expire="+date.toGMTString(); 
         } 
         document.cookie=cookieString; 
} 
//--> 
</script> 


2.获取指定名称的cookie值:getCookie(name) 
该函数返回名称为name的cookie值,如果不存在则返回空,其实现如下: 

<script language="JavaScript" type="text/javascript"> 
<!-- 
function getCookie(name){ 
         var strCookie=document.cookie; 
         var arrCookie=strCookie.split("; "); 
         for(var i=0;i<arrCookie.length;i++){ 
               var arr=arrCookie[i].split("="); 
               if(arr[0]==name)return arr[1]; 
         } 
         return ""; 
} 
//--> 

function getCookie(cookie_name){ 
    var results = document.cookie.match('(^|;) ?' + cookie_name + '=([^;]*)(;|$)'); 
    
    if (results) 
        return (unescape(results[2])); 
    else 
        return null; 
} 
</script> 


3.删除指定名称的cookie:deleteCookie(name) 
该函数可以删除指定名称的cookie,其实现如下: 

<script language="JavaS cript" type="text/javas cript"> 
<!-- 
function deleteCookie(name){ 
          var date=new Date(); 
          date.setTime(date.getTime()-10000); 
          document.cookie=name+"=v; expire="+date.toGMTString(); 

//-->
以上为js自己手动写的,现在jquery已经写了cookie的插件,所以应用起来方便很多

jquery.cookie.js

jquery中cookie插件的简单应用(网站换肤):

javascript代码如下:

<span style="white-space:pre">$().ready(function(){		</span>var $li =$("#skin li");
		$li.click(function(){
			if(this.id=='skin_0'|| this.id=='skin_1'||this.id=='skin_2'||this.id=='skin_3'||this.id=='skin_4'){
				switchSkin( this.id );
				//window.parent.location.reload();//页面加刷新
			}else {
				alert('该皮肤暂时不能使用!');
			}
			
		});	
		var cookie_skin = $.cookie("MyCssSkin");
		if (cookie_skin) {
			switchSkin(cookie_skin );
		}
					
					
		});

function switchSkin(skinName){
			$("#"+skinName).addClass("selected")                //当前<li>元素选中
						   .siblings().removeClass("selected");  //去掉其他同辈<li>元素的选中
		    $("#cssfile").attr("href","${pageContext.request.contextPath }/css/skin/"+ skinName +".css"); //设置不同皮肤
		    //兄弟框架之间的引用
		    if(document.all){//ie浏览器
		    	 window.parent.frames['mainFrame'].document.getElementById("cssfile").href = "${pageContext.request.contextPath }/css/skin/"+ skinName +".css";
		    	 if( window.parent.frames['mainFrame'].frames['I3']&&window.parent.frames['mainFrame'].frames['I3'].document){		    	 	
		    	 	if( window.parent.frames['mainFrame'].frames['I3'].document.getElementById("cssfile")){
		    	 		window.parent.frames['mainFrame'].frames['I3'].document.getElementById("cssfile").href = "${pageContext.request.contextPath }/css/skin/"+ skinName +".css";
		    	 	}
		    	 	//I3下的框架
		    	 	//资源管理iframe
		    	 	if(window.parent.frames['mainFrame'].frames['I3'].frames['I4']){
		    	 		window.parent.frames['mainFrame'].frames['I3'].frames['I4'].document.getElementById("cssfile").href= "${pageContext.request.contextPath }/css/skin/"+ skinName +".css";
		    	 	}
		    	 	//图书管理
		    	 	if(window.parent.frames['mainFrame'].frames['I3'].frames['myFrame']){
		    	 		window.parent.frames['mainFrame'].frames['I3'].frames['myFrame'].document.getElementById("cssfile").href= "${pageContext.request.contextPath }/css/skin/"+ skinName +".css";
		    	 	}
		    	 	if(window.parent.frames['mainFrame'].frames['I3'].frames['libFrame']){
		    	 		window.parent.frames['mainFrame'].frames['I3'].frames['libFrame'].document.getElementById("cssfile").href= "${pageContext.request.contextPath }/css/skin/"+ skinName +".css";
		    	 	} 		    	 	
		    	 }
		    }else {//firefox浏览器
		   		  parent.frames["mainFrame"].document.getElementById("cssfile").href = "${pageContext.request.contextPath }/css/skin/"+ skinName +".css";;// 支持ie和火狐
		   		  if(parent.frames['mainFrame'].frames['I3']){		   		  
		   		  	if(parent.frames['mainFrame'].frames['I3'].document.getElementById("cssfile")){
		   		  		parent.frames['mainFrame'].frames['I3'].document.getElementById("cssfile").href = "${pageContext.request.contextPath }/css/skin/"+ skinName +".css";		   	
		   		  	}		   		  	
		   		  	//I3下的框架
		    	 	//资源管理iframe
		    	 	if(parent.frames['mainFrame'].frames['I3'].frames['I4']){
		    	 		parent.frames['mainFrame'].frames['I3'].frames['I4'].document.getElementById("cssfile").href= "${pageContext.request.contextPath }/css/skin/"+ skinName +".css";
		    	 	}
		    	 	//图书管理
		    	 	if(parent.frames['mainFrame'].frames['I3'].frames['myFrame']){
		    	 		parent.frames['mainFrame'].frames['I3'].frames['myFrame'].document.getElementById("cssfile").href= "${pageContext.request.contextPath }/css/skin/"+ skinName +".css";
		    	 	}
		    	 	if(parent.frames['mainFrame'].frames['I3'].frames['libFrame']){
		    	 		parent.frames['mainFrame'].frames['I3'].frames['libFrame'].document.getElementById("cssfile").href= "${pageContext.request.contextPath }/css/skin/"+ skinName +".css";
		    	 	}		   		  		  
		   		  }
		    }		    
			$.cookie( "MyCssSkin" ,  skinName , { path: '/', expires: 10 });			
		}
<ul id="skin">
	<li id="skin_0" title="绿色" class="selected">蓝色</li>
	<li id="skin_1" title="深黄色">深黄色</li>
	<li id="skin_2" title="蓝色">蓝色</li>
	<li id="skin_3" title="深红色">深红色</li>
	<li id="skin_4" title="灰色">灰色</li>
	<li id="skin_5" title="淡黄色">淡黄色</li>
</ul>
分页列表多页保存多页选择的复选框的值:

写在页面加载的方法中:

<span style="white-space:pre">$(document).ready(function(){<span style="white-space:pre">	</span>		</span>
<span style="white-space:pre">		</span>var paperIds=$.cookie("ids");
				 				
		$("input[name='ids']").each(function(){		
			if(paperIds!=null){
				var p=paperIds.split("|");
					for(var i=0;i<p.length;i++){
						if($(this).val()==p[i]){
							$(this).attr("checked","true");
						}					
					}
			}	
		});
<pre name="code" class="javascript" style="background-color: rgb(255, 255, 255); ">	});

 这样在选择的时候如果选中的话,将该值添加到cookie中,如果取消选择,记得相应的从cookie中移除 

cookie中选中的值应该用一个分隔符隔开,这样在取消选择的时候,将该值 (|值|)替换成相应的值即可(替换成|),不用再重复遍历列表的值,再重新复制。详细代码就不贴了,自己写写看吧



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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值