语言选择器Cookie

时间:2016-11-21 16:26:34

标签: javascript php

我的代码无效。其目的是检查是否已为该语言设置了先前的cookie。如果没有,它会创建一个cookie来存储所选择的语言。

<script type="text/javascript">

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 + ";path=/";
}

function getCookie(cname) {
    var name = cname + "=";
    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 languageSet = getCookie("setLanguage");
    if (languageSet != "" || languageSet != null) {
        return null;
    } else {
            jQuery.fancybox("#selectFlagDiv");
            setCookie("setLanguage", setLanguage, 365);
        }
}

1 个答案:

答案 0 :(得分:0)

http://www.w3schools.com/js/js_cookies.asp

您的checkCookie逻辑错误。

function checkCookie() {
    // try and find the cookie or return empty string
    var languageSet = getCookie("setLanguage");
    // if languageSet is not the empty string then the cookie did exist 
    if (languageSet != "") {
    alert('found the cookie'+ languageSet);
        return null;
    } else {
     // otherwise set the cookie to the default value
            jQuery.fancybox("#selectFlagDiv");
            setCookie("setLanguage", 'default cookie value here', 365);
        }
}