我写了一个非常简单的javascript代码来插入cookie:
// setting the cookie value
function setCookie(cookieName, cookieValue) {
document.cookie ='prasik=bihari';
document.cookie ='pintu=tiwari';
document.cookie = cookieName + "=" + cookieValue;
document.cookie ='mykey=myvalue';
}
// retrieving the cookie value
function getCookie(cookieName)
{
var cookies = document.cookie.split(";");
//printing the cookie array on console in developer tools
console.debug(cookies);
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i];
var index = cookie.indexOf("=");
var key = cookie.substr(0, index);
var val = cookie.substr(index + 1);
if (key == cookieName)
return val;
}
}
setCookie('firstName', 'Glenn');
var firstName = getCookie('pintu');
//this prints undefined as it fails to get the key 'pintu' which has been converted to ' pintu'
console.debug(firstName);
firstName = getCookie(' pintu');
//prints the correct value
console.debug(firstName);
&#13;
在getCookie
方法内部每当我使用;
字符拆分cookie时,开发人员工具会在数组中除了第一个键之外的所有键的名称前面显示一个空格:
所以我无法使用插入cookie时用户的实际密钥'pintu'
来获取cookie值。相反,当我使用' pintu'
时,我得到了价值。有人可以解释这种奇怪的行为,或者我在我的程序中犯了错误吗?
P.S。我在Chrome和Firefox上都有这种行为。
答案 0 :(得分:0)
当您执行document.cookie
次以上时,会添加一个空格。因此,您必须将包含该空格的分隔开。
document.cookie.split("; ");