如何让document.cookie正常工作?

时间:2014-03-20 21:04:40

标签: javascript cookies

我一直在尝试将一个简单的cookie设置为当前页面,但它似乎不起作用(它没有显示我保存了cookie,并且使用document.cookie进行的任何警报都显示没有文本。

Cookies = {};

Cookies.cookiefile = blue;
Cookies.cookiekey = 5;

function Cookies.save(){
document.cookie= Cookies.cookiefile+"="+Cookies.cookiekey+";max-age="+60*60*24*10+";path=/";
alert(document.cookie);
}

1 个答案:

答案 0 :(得分:0)

现在您已经显示了实际的代码,看起来您遇到了一个脚本错误,导致代码无法运行。这段代码:

function Cookies.save(){...} 

不是声明函数的正确语法。您应该检查浏览器错误控制台或调试控制台是否存在脚本错误,它可能会向您显示。您可以使用以下格式:

Cookies.save = function() {...}

在OP提供任何代码之前提供的这部分答案。

这是一组用于处理cookie的实用程序功能。在没有看到您的代码的情况下,我们无法真正了解您做得不对,但如果您使用这些功能并尝试从允许的页面访问Cookie,则应该可以正常运行。

// createCookie()
// name and value are strings
// days is the number of days until cookie expiration
// path is optional and should start with a leading "/" 
//   and can limit which pages on your site can 
//   read the cookie.
//   By default, all pages on the site can read
//   the cookie if path is not specified
function createCookie(name, value, days, path) {
    var date, expires = "";
    path = path || "/";
    if (days) {
        date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        expires = "; expires=" + date.toGMTString();
    }
    document.cookie = name + "=" + value + expires + "; path=" + path;
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name, "", -1);
}