如果找不到Cookie,则重定向到页面

时间:2017-01-04 20:12:43

标签: javascript html cookies

如果是cookie,例如

visited
找不到

,是否可以将页面重定向到

/welcome

我从这开始:

    function getCookie(visited) {
    var dc = document.cookie;
    var prefix = visited + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1) {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    }
    else
    {
        begin += 2;
        var end = document.cookie.indexOf(";", begin);
        if (end == -1) {
        end = dc.length;
        }
    }
    return decodeURI(dc.substring(begin + prefix.length, end));
} 

function doSomething() {
    var myCookie = getCookie("visited");

    if (myCookie == null) {
        window.location.href = '/welcome';
    }
    else {
    }
}

我是否正确完成此操作,因为它在我的网站上无法正常工作。

2 个答案:

答案 0 :(得分:1)

试试PHP:

if (!isset($_COOKIE['visited'])) {
    header("Location: page.php");
}

答案 1 :(得分:1)

尝试使用

下面的checkCookie功能
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 decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.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 visited = getCookie("visited");
    if (visited != "") {
        // do whatever
    } else {
        setCookie("visited", "true", 30);
        window.location.href = '/welcome';
    }
}

有关详情,建议您访问W3SchoolsMDN