1

我尝试在 Javascript 和 Jquery 中设置和获取 Cookie,但这两种方法都返回null 。我的代码看起来正确,但我不知道为什么它对我不起作用。

厨师.js

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

function getCookie(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 deleteCookie(name) {
    setCookie(name,"",-1);
}

和我的 html 页面:

fin.html:

<!DOCTYPE html>
<html>
    <head>
        <title>My Page</title> 
        <meta name="viewport" content="width=device-width, initial-scale=1"> 
        <script type="text/javascript" src="jquery-1.7.1.min.js"></script>
        <script type="text/javascript" src="jquery.cookie.js"></script>
        <script type="text/javascript" src="cook.js"></script>
    </head>
    <body>
        <a id="setcookie" href="fin2.html">SET COOKIE</a>
        <script>
            $("#setcookie").click(function() {
                // Using javascript function
                setCookie("mycookie", "itsvalue", 1) ;

                // Using jQuery plugin
                $.cookie('myCookie2': "myValue");
            });
        </script>
     </body>
</html>

fin2.html

<!DOCTYPE html>
<html>
    <head>
        <title>My Page</title> 
        <meta name="viewport" content="width=device-width, initial-scale=1"> 
        <script type="text/javascript" src="jquery-1.7.1.min.js"></script>
        <script type="text/javascript" src="jquery.cookie.js"></script>
        <script type="text/javascript" src="cook.js"></script>      
    </head>
    <body>
        <a id="get" href="#">YOO</a>
        <script>
            $("#get").click(function() {
                alert(getCookie("mycookie")) ;
                alert($.cookie('myCookie')) ;
            }) ;
        </script>
    </body>
</html>

但它使用 jquery 插件和 javscript 的函数返回 null。你对这个问题有什么想法吗?十分感谢 :)

4

2 回答 2

1

Have you tried running this in Apache/IIS? Cookies will only be set when run from a server. I've put together a quick jsfiddle based on your code at: http://jsfiddle.net/ZuCEC/

You should be able to set, get and delete cookies and see the value changing as you go.

Hope that helps.

于 2012-05-21T15:41:18.820 回答
1

默认情况下,jQuery cookie 插件使用当前路径作为路径的默认值设置 cookie。这意味着 cookie 将仅在设置它的同一页面上可用。如果您希望 cookie 可以从您网站上的任何页面读取,请这样做。

$.cookie('the_cookie', 'the_value', { path: '/' });

另外,请注意我使用的是 a,而不是 a:

于 2012-05-21T15:03:26.570 回答