为什么浏览器会在通过javascript在cookie中插入键值对时预先设置空格

时间:2017-06-03 01:53:37

标签: javascript cookies

我写了一个非常简单的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;
&#13;
&#13;

getCookie方法内部每当我使用;字符拆分cookie时,开发人员工具会在数组中除了第一个键之外的所有键的名称前面显示一个空格:

enter image description here

所以我无法使用插入cookie时用户的实际密钥'pintu'来获取cookie值。相反,当我使用' pintu'时,我得到了价值。有人可以解释这种奇怪的行为,或者我在我的程序中犯了错误吗?

P.S。我在Chrome和Firefox上都有这种行为。

1 个答案:

答案 0 :(得分:0)

当您执行document.cookie次以上时,会添加一个空格。因此,您必须将包含该空格的分隔开。

document.cookie.split("; ");