JavaScript 设置cookie 读取cookie 举例

本文介绍了如何通过JavaScript设置和读取Cookie的具体方法。包括直接赋值的方式和使用函数实现更为复杂的设置,如指定过期时间、路径、域等属性,并提供了获取已设置Cookie的函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

设置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 进行解码。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值