javascript中應用 cookie 的 例子

來源:互聯網
上載者:User
cookie|javascript

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
               }
            }
      }


 



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.