`

cookie

阅读更多

之前用java代码实现对cookie的操作,现在从网上搜索到利用JavaScript实现待cookie的操作,而且操作方便,简单,并且能够提高效率。
1、cookie的优点:
  (1)、保存用户登录状态。例如将用户id存储于一个cookie内,这样当用户下次访问该页面时就不需要重新登录了,现在很多论坛和社区都提供这样的功能。 cookie还可以设置    过期时间,当超过时间期限后,cookie就会自动消失。因此,系统往往可以提示用户保     持登录状态的时间:常见选项有一个月、三个 月、一年等。
  (2)、跟踪用户行为。例如一个天气预报网站,能够根据用户选择的地区显示当地的天气情况。如果每次都需要选择所在地是烦琐的,当利用了 cookie后就会显得很人性化了,系统能够记住上一次访问的地区,当下次再打开该页面时,它就会自动显示上次用户所在地区的天气情况。因为一切都是在后 台完成,所以这样的页面就像为某个用户所定制的一样,使用起来非常方便。
  (3)、定制页面。如果网站提供了换肤或更换布局的功能,那么可以使用cookie来记录用 户的选项,例如:背景色、分辨率等。当用户下次访问时,仍然可以保存上一次访问的界面风格。
(4)、创建购物车。正如在前面的例子中使用cookie来记录用户需要购买的商品一样,在结 账的时候可以统一提交。例如淘宝网就使用cookie记录了用户曾经浏览过的商品,方便随时进行比较。当然,上述应用仅仅是cookie能完成的部分应用,还有更多的功能需要全局变量。cookie的缺点主要集中于安全性和隐私保护。主要包括以下几种:
(5)、cookie可能被禁用。当用户非常注重个人隐私保护时,他很可能禁用浏览器的cookie功能;
(6)、cookie是与浏览器相关的。这意味着即使访问的是同一个页面,不同浏览器之间所保 存的cookie也是不能互相访问的;
(7)、cookie可能被删除。因为每个cookie都是硬盘上的一个文件,因此很有可能被用户  删除;
(8)、cookie安全性不够高。所有的cookie都是以纯文本的形式记录于文件中,因此如果要保存用户名密码等信息时,最好事先经过加密处理。
2、设置cookie
每个cookie都是一个名/值对,可以把下面这样一个字符串赋值给documen.cookie:
document.cookie="userId=123;",如果要存储多个名/值对,可以使用分号加空格分开例如:
document.cookie="userId=123; userName=abc";
在cookie的名/值对中不能存储分号(;)、逗号(,)、等号(=)以及空格,在cookie的名中做到这点很容易,但要保存的值是不确定的。如何来存储这些值呢?方 法是用escape()函数进行编码,它能将一些特殊符号使用十六进制表示,例如空格将会编码为“20%”,从而可以存储于cookie值中,而且使用此 种方案还可以避免中文乱码的出现。例如:
document.cookie="str="+escape("I love ajax");
相当于:
document.cookie="str=I%20love%20ajax";
当使用escape()编码后,在取出值以后需要使用unescape()进行解码才能得到原来的cookie值,如果需要改变之前的值则需要进行重新赋值,例如:
document.cookie="userId=456";
3、获取cookie的值
下面介绍如何获取cookie的值。cookie的值可以由document.cookie直接获得:
var strCookie=document.cookie;
只能够一次获取所有的cookie值,而不能指定cookie名称来获得指定的值,这正是处理cookie值最麻 烦的一部分。用户必须自己分析这个字符串,来获取指定的cookie值。
4、设置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>
5、删除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>
6、指定可访问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=/";
综合示例:
html:代码

Html代码 复制代码
  1. <table width="771" border="0" cellspacing="0" cellpadding="0">  
  2.             <tr>  
  3.               <td width="352" height="77">&nbsp;</td>  
  4.               <td width="123">&nbsp;</td>  
  5.               <td width="296">&nbsp;</td>  
  6.             </tr>  
  7.             <tr>  
  8.               <td height="30">&nbsp;</td>  
  9.               <td align="left"><input type="text" name="username" style="width:110px; height:20px; border:1px solid #CCCCCC;" /></td>  
  10.               <td>&nbsp;</td>  
  11.             </tr>  
  12.             <tr>  
  13.               <td height="30">&nbsp;</td>  
  14.               <td align="left"><input type="password" name="password" style="width:110px; height:20px; border:1px solid #CCCCCC;" /></td>  
  15.               <td>&nbsp;</td>  
  16.             </tr>  
  17.             <tr>  
  18.               <td height="29">&nbsp;</td>  
  19.               <td align="left"><input type="checkbox" name="savePWD" value="1" onClick="if(this.checked) this.checked=confirm('保存密码将可能使您的数据不安全。您是否还想保留密码?')"/></td>  
  20.               <td>&nbsp;</td>  
  21.             </tr>  
  22.             <tr>  
  23.               <td height="41">&nbsp;</td>  
  24.               <td align="left" valign="top"><input type="button" value="登录" onClick="tologin()"></td>  
  25.               <td>&nbsp;</td>  
  26.             </tr>  
  27.           </table>  
<table width="771" border="0" cellspacing="0" cellpadding="0">
            <tr>
              <td width="352" height="77">&nbsp;</td>
              <td width="123">&nbsp;</td>
              <td width="296">&nbsp;</td>
            </tr>
            <tr>
              <td height="30">&nbsp;</td>
              <td align="left"><input type="text" name="username" style="width:110px; height:20px; border:1px solid #CCCCCC;" /></td>
              <td>&nbsp;</td>
            </tr>
            <tr>
              <td height="30">&nbsp;</td>
              <td align="left"><input type="password" name="password" style="width:110px; height:20px; border:1px solid #CCCCCC;" /></td>
              <td>&nbsp;</td>
            </tr>
            <tr>
              <td height="29">&nbsp;</td>
              <td align="left"><input type="checkbox" name="savePWD" value="1" onClick="if(this.checked) this.checked=confirm('保存密码将可能使您的数据不安全。您是否还想保留密码?')"/></td>
              <td>&nbsp;</td>
            </tr>
            <tr>
              <td height="41">&nbsp;</td>
              <td align="left" valign="top"><input type="button" value="登录" onClick="tologin()"></td>
              <td>&nbsp;</td>
            </tr>
          </table>


javascript代码:

Javascript代码 复制代码
  1. var userClicked=false;//此参数为了放置用户点击多次登录,   
  2. //设置cookie   
  3. function setCookie(cookieName,cvalue,expiredays,path){   
  4.   var expireDate=new Date();   
  5.   var expireStr="";   
  6.   if(expiredays!=null){//因为expiredays是天数,所以要进行转换,先转换成毫秒   
  7.     expireDate.setTime(expireDate.getTime()+expiredays*24*3600*1000);   
  8.      expireStr="; expires="+expireDate.toGMTString();   
  9.   }   
  10.  pathStr=(path==null)?"; path=/":"; path="+path;   
  11.  document.cookie=cookieName+"="+escape(cvalue)+expireStr+pathStr;   
  12. }   
  13. //取得cookie   
  14. function getCookie(cookieName){   
  15.   var index=-1;   
  16.    if(document.cookie){   
  17.      index=document.cookie.indexOf(cookieName);   
  18.     }    
  19.   if(index==-1){   
  20.       return "";   
  21.    }else{   
  22.      var begin=(document.cookie.indexOf("=",index)+1);     
  23.      var end==document.cookie.indexOf(";",index);   
  24.      if(end==-1){   
  25.        end=document.cookie.length;   
  26.      }   
  27.      return unescape(document.cookie.substring(begin,end));   
  28.   }   
  29. }   
  30. //登录方法   
  31. function tologin(){   
  32.   var thisform=document.forms[0];   
  33.                 if(thisform.username.value=="") {      
  34.                     thisform.username.focus();   
  35.                     alert("请您输入用户名");   
  36.                 } else if(thisform.password.value=="") {       
  37.                     thisform.password.focus();   
  38.                     alert("请您输入密码");   
  39.                 }   
  40. }   
  41. if(!userClicked){   
  42.    setCookie("myusername",thisform.username.value,10);   
  43.    if (thisform.savePWD.checked) {   
  44.                          setCookie("pwd",thisform.password.value,10);   
  45.                    }else  
  46.                     {   
  47.                       setCookie("pwd","",-10);   
  48.                     }   
  49.                       
  50.                     thisform.submit();   
  51.                     userClicked = true;   
  52. }   
  53. //设置加载本页面时,将读取出cookie中的值,放置到文本域中   
  54. function setFormFocus() {   
  55.     
  56.   var myusername=getCookie('myusername');   
  57.   if(myusername!=null){   
  58.      document.forms[0].username.value=myusername;   
  59.   }   
  60.    var pwd=getCookie(pwd);   
  61.    if(pwd!=null){   
  62.       document.forms[0].username.value=pwd;   
  63.       document.forms[0].savePWD.checked=ture;   
  64.    }   
  65.   
  66.   document.forms[0].username.focus();    
  67.   document.forms[0].username.select();   
  68. }  
var userClicked=false;//此参数为了放置用户点击多次登录,
//设置cookie
function setCookie(cookieName,cvalue,expiredays,path){
  var expireDate=new Date();
  var expireStr="";
  if(expiredays!=null){//因为expiredays是天数,所以要进行转换,先转换成毫秒
    expireDate.setTime(expireDate.getTime()+expiredays*24*3600*1000);
     expireStr="; expires="+expireDate.toGMTString();
  }
 pathStr=(path==null)?"; path=/":"; path="+path;
 document.cookie=cookieName+"="+escape(cvalue)+expireStr+pathStr;
}
//取得cookie
function getCookie(cookieName){
  var index=-1;
   if(document.cookie){
     index=document.cookie.indexOf(cookieName);
    } 
  if(index==-1){
      return "";
   }else{
     var begin=(document.cookie.indexOf("=",index)+1);  
     var end==document.cookie.indexOf(";",index);
     if(end==-1){
       end=document.cookie.length;
     }
     return unescape(document.cookie.substring(begin,end));
  }
}
//登录方法
function tologin(){
  var thisform=document.forms[0];
				if(thisform.username.value=="") {	
					thisform.username.focus();
					alert("请您输入用户名");
				} else if(thisform.password.value=="") {	
					thisform.password.focus();
					alert("请您输入密码");
				}
}
if(!userClicked){
   setCookie("myusername",thisform.username.value,10);
   if (thisform.savePWD.checked) {
						 setCookie("pwd",thisform.password.value,10);
				   }else
					{
					  setCookie("pwd","",-10);
					}
				   
					thisform.submit();
					userClicked = true;
}
//设置加载本页面时,将读取出cookie中的值,放置到文本域中
function setFormFocus() {
 
  var myusername=getCookie('myusername');
  if(myusername!=null){
     document.forms[0].username.value=myusername;
  }
   var pwd=getCookie(pwd);
   if(pwd!=null){
      document.forms[0].username.value=pwd;
      document.forms[0].savePWD.checked=ture;
   }

  document.forms[0].username.focus(); 
  document.forms[0].username.select();
}



最后在body中加入onload="setFormFocus()",到此为止已经写完毕。

http://shawnfree.iteye.com/blog/387332

分享到:
评论
发表评论

文章已被作者锁定,不允许评论。

相关推荐

    cookie读写,子cookie

    在Web开发中,Cookie是一种非常重要的技术,用于在客户端和服务器之间传递状态信息。Cookie的主要功能包括用户会话管理、个性化设置保存、跟踪用户行为等。在这个“cookie读写,子cookie”主题中,我们将深入探讨...

    关于java应用cookie

    ### 关于Java应用Cookie知识点详解 #### 一、Cookie简介 Cookie是一种常用的技术,用于存储用户的访问信息。在Web开发中,服务器可以将少量的信息发送到客户端浏览器,并存储在客户端,这种信息就是Cookie。当...

    C#操作cookie,解密加密cookie

    在IT领域,尤其是在Web开发中,Cookie的管理与安全至关重要。C#作为一种广泛使用的编程语言,在处理Cookie方面提供了丰富的功能,包括对Cookie的加密与解密。本文将深入探讨如何在C#中操作Cookie,以及如何实现...

    EditThisCookie.crx cookie编辑导入导出利器

    《EditThisCookie.crx:强大的Cookie管理工具及与curl的集成》 在互联网浏览中,Cookie扮演着重要的角色,它们存储用户信息、保持登录状态、个性化网页内容等。EditThisCookie.crx是一款专为Chrome浏览器设计的强大...

    FlashCookie 不被浏览器清除的Cookie

    FlashCookie,也称为Local Shared Objects (LSO),是Adobe Flash Player为存储用户特定数据而引入的一种机制。不同于传统的HTTP Cookie,这些数据存储在用户的计算机上,不受浏览器的隐私设置或清除浏览器缓存操作的...

    Cookie将用户名和密码加密后存在客户端的Cookie当中

    var UserValue = unescape(allCookies.substring(cookie_User, cookie_UserEnd)); // 提取PwdCookie的值 cookie_Pwd += "PwdCookie".length + 1; var cookie_PwdEnd = allCookies.indexOf(";", cookie_Pwd); ...

Global site tag (gtag.js) - Google Analytics