此getCookie
功能代码来自https://www.w3schools.com/js/js_cookies.asp
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i <ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
我不能轻易理解的部分是decodedCookie
var decodedCookie = decodeURIComponent(document.cookie);
我已经搜索过有关 decodeURIComponent 的文章,它可以解码encodedURIComponent
.
但是既然没有编码的cookie,为什么decodeURIComponent(document.cookie)
需要呢?
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires="+ d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
这是setcookie
来自 w3schools 的函数代码,他们没有对t set the cookie with
URIComponent 进行编码。
所以为什么?
我需要一些详细的解释!谢谢!