cookie 不存储,有什么想法吗?

cookie not storing, any ideas?

我正在尝试根据用户输入创建、检查和获取 cookie,但是当我输入我的名字时,它不会保存 cookie,因此我不知道我的检查或获取功能是否有效。有什么想法吗?

这是我的代码:

//capture the values and write to a cookie
function setCookie(Name, Value, Expiration) {

    //set the expiry date 
    var expDate = new Date();

    //check if the expiration parameter is not null
    if (Expiration !== null) {
        expDate.setDate(expDate.getDate() + Expiration);

        //write the data to store
        var cookieVal = escape(Value) + "; expires=" + expDate.toGMTString() + ";";

        //store the cookie
        document.cookie = Name + "=" + cookieVal;
    } else {
        alert("expiration is invalid"); 
    }
}

function getCookie(Name) {

    //capture all cookies and split into individual ones
    var cookies=document.cookie.split(";"); 

    //process each one
    for(var i=0; i<cookies.length; i++){

        //obtain the name of the cookie
        var CName = cookies[i].substr(0,cookies[i].indexOf("="));   

        //obtain the value of the cookie
        var CValue = cookies[i].substr(cookies[i].indexOf("=") + 1);

        //replace any escaped characters
        CName = CName.replace(/^\s+|\s+$/g, "");

        //if the name of the cookie matches the name that was passed by the caller, return the associated cookie

        if(Name == CName) {
            return unescape(CValue);    
        }
    }

    //return a null value if the cookie isnt found
    return null;
}

function checkName() {
    //obtain the users name
    var UserName = getCookie("Username");

    //check for a user name
    if((UserName == null) || (UserName == "")) {

        //obtain a username from the user
        UserName = prompt("please type your name");

        //set a cookie for the username
        setCookie("UserName", UserName, 365);   
    } else {
        UserName = "welcome back " + UserName;  
    }

    //display the users name on screen
    var SetName = document.getElementById("name");
    SetName.innerHTML = "hello " + UserName;
}

@RGraham 给出了下面的答案,现在看来有效。

Simple typo: setCookie("UserName", UserName, 365); yet you are checking for Username ... var UserName = getCookie("Username");

谢谢。