在javascript中设置和检索cookie

时间:2014-12-31 13:23:45

标签: javascript

所以我正在学习Javascript并试图设置和检索一个cookie,我的代码看起来都没问题,但这里显然存在问题。

function init()
{
    var panel = document.getElementById("panel");

    var user = escape("Dan, 000456");
    var expiry = new Date();
    expiry.setTime(expiry.getTime() + (7*24*60*1000) );
    document.cookie = "myData=" + user + ";" + "expires=" + expiry.toGMTString() + ";";

    if (document.cookie)
    {
        var cookieString = unescape(document.cookie);
        var list = cookieString.split("=");
        if (list[0] === "myData")
        {
            var data = list[1].split(",");
            var userName = data[0];
            var userAcct = data[1];
        }
    }

    panel.innerHTML += "Cookie String:" + cookieString;
    panel.innerHTML += "<br>Split List:" + list;
    panel.innerHTML += "<br>User Name:" + userName;
    panel.innerHTML += "<br>User Account:" + userAcct;
}
document.addEventListener("DOMContentLoaded",init, false);

当我查看结果时,他们不是我期待看到的:

Cookie String:undefined
Split List:undefined
User Name:undefined
User Account:undefined

1 个答案:

答案 0 :(得分:1)

现在您的主要问题是您已经更正了语法错误,如下所示:

var user = escape(“Dan,000456”);

注意:我认为现在不推荐使用转义函数了吗?

将您的javascript更改为此并确保您的浏览器允许使用Cookie:

    function init(){

    var panel = document.getElementById("panel");

    var user = ["Dan, 000456"];  //<--change #1
    var expiry = new Date();
    expiry.setTime(expiry.getTime() + (7*24*60*1000) );

    //change #2 below added the array index of user to set the cookie value for myData
    document.cookie = "myData=" + user[0] + ";" + "expires=" + expiry.toGMTString();



    if (document.cookie)
    {
        var cookieString = unescape(document.cookie);
        var list = cookieString.split("=");
        if (list[0] === "myData")
        {
            var data = list[1].split(",");
            var userName = data[0];
            var userAcct = data[1];
        }
    }

    panel.innerHTML += "Cookie String:" + cookieString;
    panel.innerHTML += "<br>Split List:" + list;
    panel.innerHTML += "<br>User Name:" + userName;
    panel.innerHTML += "<br>User Account:" + userAcct;
           }
document.addEventListener("DOMContentLoaded",init, false);

还要确保你的html看起来像这样:

<div id="panel">Test</div>

如果需要,您可以从上面html中的div中删除Test。 Test值应替换为panel.innerHTML赋值中的值。