[英]Javascript getCookie function doesn't work properly
I'm simply trying to read a cookie's value, but I seem to be doing something wrong, but I don't see the problem.我只是想读取 cookie 的值,但我似乎做错了什么,但我没有看到问题所在。 The cookie does get properly stored and can be accessed under document.cookie
, so that's not the problem. cookie 确实得到了正确存储,并且可以在document.cookie
下访问,所以这不是问题所在。 Here's my JS code:这是我的 JS 代码:
function getCookie(name) {
const value = `; ${document.cookie}`;
const parts = value.split(`; ${name}=`);
if (parts.length === 2) return parts.pop().split(';').shift();
}
var value = getCookie(value);
console.log(value);
console.log(document.cookie);
d = new Date('20 Oct 2022')
function setCookie() {
document.cookie = `value=10000; expires=${d.toUTCString()}`;
console.log("cookie set!");
}
edit: I found my problem.编辑:我发现了我的问题。 I was missing the quotation marks… I've never felt this stupid:D我漏掉了引号……我从来没有觉得这么蠢:D
You can use this function:您可以使用此 function:
function getCookie(cname) {
let name = cname + "=";
let decodedCookie = decodeURIComponent(document.cookie);
let ca = decodedCookie.split(';');
for (let i = 0; i < ca.length; i++) {
let c = ca[i];
while (c.charAt(0) === ' ') {
c = c.substring(1);
}
if (c.indexOf(name) === 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.