JavaScript: 設定Cookie

來源:互聯網
上載者:User

JavaScript Cookie是一種適合用戶端的、便利的持久性的資料存放區方案。Cookie是一個名值對的列表,每個名值對以分號(;)隔開。下面介紹3個可重用的Cookie方法:

function writeCookie(name, value, days) {
  // By default, there is no expiration so the cookie is temporary
  var expires = "";

  // Specifying a number of days makes the cookie persistent
  if (days) {
    var date = new Date();
    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
    expires = "; expires=" + date.toGMTString();
  }

  // Set the cookie to the name, value, and expiration date
  document.cookie = name + "=" + escape(value) + expires + "; path=/";
}

function readCookie(name) {
  // Find the specified cookie and return its value
  var searchName = name + "=";
  var cookies = document.cookie.split(';');
  for(var i=0; i < cookies.length; i++) {
    var c = cookies[i];
    while (c.charAt(0) == ' ')
      c = c.substring(1, c.length);
    if (c.indexOf(searchName) == 0)
      return unescape(c.substring(searchName.length, c.length));
  }
  return null;
}

function eraseCookie(name) {
  // Erase the specified cookie
  writeCookie(name, "", -1);
}

 

一點點說明:

1. Cookie的名值不能使用分號(;)逗號(,)等號(=)以及空格,在name中容易保證這個規則,但是value很難保證,因此這裡用escape函數進行編碼,將value中的特殊字元用十六進位表示,如空格為"20%"。 同理讀Cookie的值時,用unescape進行解碼

2. 設定Cookie使用document.cookie="...",雖然cookie看上去像一個屬性,但它和一般的屬性不一樣,改變它的賦值並不意味著丟失原來的值,而是新增加了一個Cookie.改變一個Cookie的賦值,只需要重新賦值即可。

樣本:

writeCookie("username", "test");

writeCookie("password", "111");

這裡建立了兩個cookie:username和password,如果password發生改變,如變為"222",則writeCookie("password","222")將覆蓋已有Cookie的值。

3. 刪除Cookie,這裡將Cookie的到期時間設定為前一天結束,因此該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.