syc001 发表于 2013-1-22 22:33:50

JavaScript 设置cookie 读取cookie 举例

设置cookie:

赋值实现:
每个cookie都是一个名/值对,可以把下面这样一个字符串赋值给document.cookie:
document.cookie="userId=828";
如果要一次存储多个名/值对,可以使用分号加空格(; )隔开,例如:
document.cookie="userId=828; userName=hulk";

函数实现:
function setCookie(sName, sValue, days, sPath, sDomain, bSecure) {
    var sCookie = sName + "=" + encodeURIComponent(sValue);

    if (days) {
var oExpires = new Date();
oExpires.setTime(oExpires.getTime() + days*24*60*60*1000);
      sCookie += "; expires=" + oExpires.toGMTString();
    }

    if (sPath) {
      sCookie += "; path=" + sPath;
    }

    if (sDomain) {
      sCookie += "; domain=" + sDomain;
    }

    if (bSecure) {
      sCookie += "; secure";
    }
    document.cookie = sCookie;
}

其中:
encodeURIComponent为JavaScript encodeURIComponent() 函数
用法
encodeURIComponent() 函数可把字符串作为 URI 组件进行编码。

读取cookie:
function getCookie(sName) {
    var sRE = "(?:; )?" + sName + "=([^;]*);?";
    var oRE = new RegExp(sRE);
    if (oRE.test(document.cookie)) {
      return decodeURIComponent(RegExp["$1"]);
    } else {
      return null;
    }
}
其中:
decodeURIComponent为JavaScript decodeURIComponent() 函数
用法
decodeURIComponent() 函数可对 encodeURIComponent() 函数编码的 URI 进行解码。
页: [1]
查看完整版本: JavaScript 设置cookie 读取cookie 举例