JavaScript 實現Cookie 的寫入和讀取

來源:互聯網
上載者:User

cookie是網頁通過瀏覽器儲存在使用者本機電腦上的資料,使用者再次訪問該網頁的時候,瀏覽器會將這資料發送給該網頁。

Cookie最典型的應是判斷註冊使用者是否已經登陸網站。使用者可能會得到提示,是否在一下次進入此網站的時候保留使用者資訊以便簡化登陸手續,也就是“記住密碼”,這些所謂的記憶都是用cookie儲存的。另一個重要的應用場合是“購物車之類的處理”,使用者可能會在一段時間內在同一家的不同頁面選擇不同的商品,網頁把這些資訊寫入到cookie,以便在付款時候提取資訊。

在js中我們用document.cookie這屬性來寫入cookie和讀取cookie

 

寫入cookie的格式:document.cookie='cookiename='+escape('cookievalue')+';expires='+ dataobj.toGMTString()

View Code

 function writeCookie() {
var vdate = new Date();
document.cookie = "name=" + escape('寫入cookie') + ';expires=' + vdate.setTime(vdate.getTime() + 1 * 24 * 60 * 60 * 1000).toGMTString();
}
function readCookie() {
var cookieValue = document.cookie;
var start = cookieValue.indexOf('name=');
if (start != -1) {
start += 'name'.length + 1;
var end = cookieValue.indexOf(';', start);
if (end == -1) {
alert(unescape(cookieValue.substring(start)));
}
else {
alert(unescape(cookieValue.substring(start, end)));
}
}
}

  

 

 

相關文章

聯繫我們

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