cookie的使用,cookie使用

來源:互聯網
上載者:User

cookie的使用,cookie使用

通過date設定到期時間

date通過setDate(當前date+到期時間)來完成到期日期的設定

具體使用如下:

var myDate=new Date();myDate.setDate(myDate.getDate()+14);dateStr=myDate.getFullYear()+'-'+(myDate.getMonth()+1)+'-'+myDate.getDate();alert(dateStr);
其中 myDate.setDate(myDate.getDate()+14)不僅僅可以設定天數,還可以利用getSecond()擷取秒數,把到期天數換算成秒數來設定到期時間


FF瀏覽器可以支援本地網站cookie的查看,所以測試時,最好用FireFox瀏覽器。查看方法如下:

對網頁右擊》》查看頁面資訊》》安全》》查看cookie

設定cookie函數如下:

function setCookie(name,value,expiresDay){var date=new Date();date.setDate(date.getDate()+expiresDay);document.cookie=name+'='+value+'; expires='+date;}

其中expires是設定到期時間,中間使用“分號+空格”來隔開


讀取cookie函數如下:

function getCookie(name){var cookies=document.cookie.split('; ');for(var i=0;i<cookies.length;i++){var userData=cookies[i].split('=');if(userData[0]==name){return userData[1];}}return '';}
cookie在使用者硬碟上是以'user=zhaoshaobang; password=123456'格式進行儲存的,中間使用“分號+空格”進行隔開的。

所以可以使用split將讀取到的cookie進行分割,這樣數組裡儲存的就是 user=zhaoshaobang,password=123456了。然後再使用split('=')分割出變數名和變數值,將要讀取的name與變數名比較,就可以讀取相應的cookie值了。

如果想要把某一個cookie到期,就可以使用 setCookie(name,value,-1),對應的cookie就會被刪除掉。


下面就應用這節學的,做一個執行個體

html代碼如下:

<form id="form1" action="http://by.cuc.edu.cn">使用者名稱:<input name="user" /><br />密碼:<input name="pass" /><br /><input type="submit" value="登入" /></form>

js代碼如下:

window.onload=function(){var oForm=document.getElementById('form1');var username=document.getElementsByName('user')[0];var password=document.getElementsByName('pass')[0];oForm.onsubmit=function(){setCookie('username',username.value,14);setCookie('password',password.value,2);};username.value=getCookie('username');};

這個執行個體就實現了我們的使用者登入,通過在window.onload中調用cookie,來讀取使用者名稱,如下



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.