获取cookie值的问题

时间:2014-11-02 03:26:33

标签: javascript jquery cookies

我正在进行一项任务,用户可以在文本框中输入他们的名字,然后选择带有单选按钮的图片,验证并将值存储在cookie中。

虽然没有完美执行,但我看到cookie只是通过打印document.cookie正确存储。我现在想要做的只是显示值而不是cookie名称。就像现在一样,没有任何东西可供我使用。我怀疑问题出在我的GetCookie函数中或从中调用它。

任何指针都将不胜感激!

// Functions
$("#BtnSubmit").click(function () {
    ClearErrors();
    Validate();
});

$("#BtnShow").click(function () {
    GetCookie(document.cookie);

});

$("#BtnDestroy").click(function () {
    DestroyCookie();
});

function Validate() {
    var name = $("#TBName").val();
    var pic = $("input:radio[name='RGPic']:checked").val();
    var isValid = true;
    // validate name field
    var nameReg = /^[A-Za-z ]{3,20}$/;
    if (!nameReg.test(name) || name.length == 0) {
        $("#DivNameError").html("C'mon, \"" + name + "\" is not a valid name.");
        isValid = false;
    }
    if (name.length == 0) {
        $("#DivNameError").html("No name was entered!");
        isValid = false;
    }

    // Validate picture selected
    if (pic == undefined) {
        $("#DivPicError").html("Select a picture");
        isValid = false;
    }
    if (isValid == true) {
        SetCookie(name, pic);
    }
}

// function to clear error messages upon attempted submittal
function ClearErrors() {
    $("#DivNameError").html("");
    $("#DivPicError").html("");
}

// Cookie Functions
function SetCookie(nValue, picture) {
    document.cookie = "name=" + nValue + "; expires=Wed, 01 Jan 2020 00:00:00 GMT; path=/";
    document.cookie = "securitypicture=" + picture + "; expires=Wed, 01 Jan 2020 00:00:00 GMT; path=/";
    $("#DivMessage").show().html("Cookie has been added.").fadeOut(1600);
    window.location.href = "results.html";
}

function GetCookie(list) {
    var cookieArr = new array();
    cookieArr = list.split(";");
    for (var i = 0; i < cookieArr.length; i++) {
        var val = cookieArr[i].split("=");
    }
    $("#DivCookieContents").html("name value: " + val[0] + "picture file: " + val[1]);
}

function DestroyCookie() {
    var name = "";
    var pic = "";
    SetCookie(name, pic);
}

1 个答案:

答案 0 :(得分:0)

您的DestroyCookie函数应将name作为参数,并将过期日期设置为过去的日期。

function DestroyCookie(name) {
    document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT;';
}

GetCookie

function GetCookie(list) {   
    var cookieArr = new array();
    cookieArr = list.split(";");
    var cookieStr = ""
    for (var i = 0; i < cookieArr.length; i++) {
        val = cookieArr[i].split("=");
        cookieStr += "name value: " + val[0] + "picture file: " + val[1] + "<br/>"
    }
    $("#DivCookieContents").html(cookieStr);
}