保存cookie的问题

时间:2013-01-10 00:52:16

标签: javascript html cookies

我是javascript的新手,我在编写Cookie时遇到问题。这是我的代码

    function writeCookie(name, value, days){
        var cookie_expires;
        if (days) {
            var date = new Date();
            date.setTime(date.getTime()+(days*24*60*60*1000));
            cookie_expires = "; expires=" + date.toGMTString();
}
else {
    cookie_expires = "";
}
document.cookie = name + "=" + value + cookie_expires;

    }

然后如果我调用此函数

function check(){
      alert("all cookies"+document.cookie);
 }
它没有给我什么。有人能帮助我吗?

1 个答案:

答案 0 :(得分:0)

尝试使用这些函数来编写和获取cookie:

function setCookie(c_name,value,exdays)
{
    var exdate=new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
    document.cookie=c_name + "=" + c_value;
}

function getCookie(c_name)
{
    var i,x,y,ARRcookies=document.cookie.split(";");
    for (i=0;i<ARRcookies.length;i++)
    {
       x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
       y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
       x=x.replace(/^\s+|\s+$/g,"");
       if (x==c_name)
       {
           return unescape(y);
       }
    }
}