0
点赞
收藏
分享

微信扫一扫

javascript中应用 cookie 的 例子


java中的cookie使用时非常的广泛的,尤其一些 在线 影音 播放的网站, 一般都是用服务器段脚本将 影音文件的名字 放到cookie中,然后在客户段 用 javascript 读取 。这样可以隐蔽 文件的名字,防止下载。

下面就把一个javascript中使用 cookie的例子发出来。大家共同学习。

 写 cookie


var 
   expiresTime 
  = 
  new 
   Date();
         expiresTime.setTime(expiresTime.getTime()  
  + 
    
  3000 
  ); 
  // 
  保存3秒钟 
  
 
           document.cookie 
  = 
  " 
  cookie_northsnow= 
  " 
    
  + 
   escape( 
  " 
  我是 塞北的雪 
  " 
  )  
  + 
    
  " 
  ;expires= 
  " 
    
  + 
   expiresTime.toGMTString();
 


读 cookie 


   
         var 
   strCookie 
  = 
  unescape(document.cookie);
         var 
   strTT 
  = 
  " 
  cookie_northsnow= 
  " 
  ;
         if 
  (strCookie.indexOf(strTT) 
  >= 
  0 
  )
         ... 
  {
            var strT1=strCookie.substring(strCookie.indexOf(strTT) + strTT.length)
            var strT2=strT1.substring(0,strT1.indexOf(";")) 
            alert(strT2);
      }

 

但是对于由服务器端写入的cookie  数组 怎么办呢?

比如:response.Cookies("cookie_northsnow")("name")=  "I am NorthSnow!"

读取这个cookie 的代码如下:


var    strCookie 
  = 
  unescape(document.cookie);
         var    strTT 
  = 
  " 
  cookie_northsnow=name= 
  " 
  ;
         if   (strCookie.indexOf(strTT) 
  >= 
  0 
  )
         ...   {
            var strT1=strCookie.substring(strCookie.indexOf(strTT) + strTT.length)
            var strT2=strT1.substring(0,strT1.indexOf(";")) 
            alert(strT2.replace(/+/gi," "));
      }

但是对于有多个成员的数组,则需要对字符串进行仔细的分割。例如 cookie 数组是这样产生的:

response.Cookies("cookie_northsnow")("name")=  "塞北的雪"
response.Cookies("cookie_northsnow")("age")=  "而立之年"
response.Cookies("cookie_northsnow")("sex")=  "男子汉大豆腐"

则需要要这样的代码进行获取:


var    strCookie   = 
  new 
   String();
      strCookie   =   unescape(document.cookie);
      strTT   =   "   cookie_northsnow= 
  " 
  
         if   (strCookie.indexOf(strTT)   >= 
  0 
  )
         ...   {
      
            var strT1=new String();
            var strS=new String();
            var arrStr=new Array()
            strT1=strCookie.substring(strCookie.indexOf(strTT) + strTT.length)
            arrStr=strT1.split("&");
            for(var i=0;i<arrStr.length;i++)
            ...{
               strS=arrStr[i];
               switch(strS.substring(0,strS.indexOf("=")))
               ...{
                 case "name": alert("姓名===" + strS.substring(strS.indexOf("=")));break
                 case "age": alert("年龄===" + strS.substring(strS.indexOf("=")));break
                 case "sex": alert("性别===" + strS.substring(strS.indexOf("=")));break
               }
            }
      }

举报

相关推荐

0 条评论