cookie没有在javascript中设置

时间:2015-07-31 00:09:10

标签: javascript cookies

我遇到了为cookie设置值的问题。每次我运行我所做的功能时,总是会返回未定义的cookie值。这是我的代码:

login.html -

function setCookie(cname, cvalue, exdays) {
    var d = new Date();

    d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));

    var expires = "expires=" + d.toUTCString();

    document.cookie = cname + "=" + cvalue + "; " + expires;
}

$('#submit').click(function() {
    if ($('#username').val() != "" && $('#password').val() != "") {
        // set the cookie 
        // and redirect
        setCookie("username", $('#username').val(), 365);

        window.location = "profile.html";
    } else {
        alert("All fields must be filled out");
    }
});

并在profile.html页面上:

function getCookie(cookie_name) {
    var name = cookie_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);

         if (c.indexOf(name) == 0) return c.substring(name.length, c.length);   
    }
   return ""; 
}


function checkCookie() {
    var user = getCookie("username");

    if (user != "") {
        $('#user_greet').html("<b>Welcome " + user + "</b>");   
    } else {
       alert("You are not allowed to be here");
        window.location = "login.html"; 
    } 
}

$(document).ready(function() {
   checkCookie();
});

任何帮助都将不胜感激。

谢谢!

0 个答案:

没有答案