Cookie组成

  1. //在http的header信息中,Header的信息格式如下
  2. Set-Cookie: name=value; [expires=date]; [path=path];
  3. [domain=domainname]; [secure];
  4. //在http代码中的具体例子
  5. <meta http-equiv="set-cookie" content=" cookieName = cookieValue;
  6. expires=01-Dec-2006 01:14:26 GMT; path=/" />

具体组成形式

  • Name/value对

由分号分隔,一个Cookie最多有20对,每个网页最多有一个CookieValue的长度不超过4K。对于Value值,最好用encodeURIComponent对其编码。

  • Domain
    默认情况下,用户访问网页的域名会存放在Cookie中。如果设置了这个Cookie的域名值,那么意味着域名上的所有服务器,而不仅是你正在访问的服务器,都能访问这个Cookie,通常不要这样做。设置域名的格式如下:domain=http://xyz.com

  • path
    设置对于特定的服务器来说哪个目录中的网页可访问Cookie,设置path的格式是:path = /movies

  • expires
    设置Cookie存活的时间,默认情况下,用户关闭浏览器则Cookie自动删除,如果没有设置Cookie失效的时间,那么用户关闭浏览器时Cookie也消失。如果设置该项,就能延长Cookie的生命期。设置时间在JS 中用Date对象的GMT形式,格式如下: expires = date.toGMTString()

  • Secure
    true或者false值。如果为true,那么必须通过https发送Cookie

创建Cookie

  1. //一般cookie
  2. document.cookie = "username=Daisy Green";
  3. //有过期时间的cookie
  4. document.cookie = "username=Daisy Green; expires=Mon, 26 Aug 2019 12:00:00 UTC";
  5. //有路径的cookie
  6. document.cookie = "username=Daisy Green; expires=Mon, 26 Aug 2019 12:00:00 UTC"; path=/";

读取Cookie

  1. var x = document.cookie;

实例1

  1. function ReadCookie() {
  2. var allcookies = document.cookie;
  3. document.write ("All Cookies : " + allcookies );
  4. // Get all the cookies pairs in an array
  5. cookiearray = allcookies.split(';');
  6. // Now take key value pair out of this array
  7. for(var i=0; i<cookiearray.length; i++) {
  8. name = cookiearray[i].split('=')[0];
  9. value = cookiearray[i].split('=')[1];
  10. document.write ("Key is : " + name + " and Value is : " + value);
  11. }
  12. }

改变Cookie和创建一样

  1. function WriteCookie() {
  2. var now = new Date();
  3. now.setMonth( now.getMonth() + 1 );
  4. cookievalue = escape(document.myform.customer.value) + ";"
  5. document.cookie = "name=" + cookievalue;
  6. document.cookie = "expires=" + now.toUTCString() + ";"
  7. document.write ("Setting Cookies : " + "name=" + cookievalue );
  8. }

删除Cookie

  1. //直接把过期时间设置为过去的时间即可
  2. document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";