【问题标题】:Redirect to page if cookie is not found如果未找到 cookie,则重定向到页面
【发布时间】:2017-01-05 04:54:03
【问题描述】:

例如,如果是 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 {
    }
}

我这样做是否正确,因为它在我的网站上无法正常工作。

【问题讨论】:

  • 你能分享一些你已经开始的代码吗?
  • 是的............
  • 在 Loaf 中添加代码
  • 自从您添加代码后,我将反对反对票。你有没有打电话给doSomething()
  • 那可能是我出错的地方

标签: javascript html cookies


【解决方案1】:

试试 PHP:

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

【讨论】:

  • 抱歉,如果找不到 cookie 应该是:if (!isset($_COOKIE['visited']))
【解决方案2】:

尝试使用下面的这个 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

【讨论】:

  • @LewisMilburn - 我编辑了我的答案以添加在 W3Schools 上使用的 set cookie 方法
猜你喜欢
  • 2021-10-07
  • 1970-01-01
  • 1970-01-01
  • 2021-05-06
  • 2012-10-09
  • 1970-01-01
  • 2019-12-06
  • 2015-10-27
  • 2014-06-10
相关资源
最近更新 更多