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