【问题标题】:redirection cookie stuck in loop重定向cookie卡在循环中
【发布时间】:2012-02-06 16:59:21
【问题描述】:

由于某种原因,此脚本卡在重定向循环中,不会让您离开“android.html”。 url 栏显示它正在尝试转到“index.html”,但它只是闪烁然后停留在“android.html”

    var caution = false

function setCookie(name, value, expires, path, domain, secure) {
    var curCookie = name + "=" + escape(value) +
            ((expires) ? "; expires=" + expires.toGMTString() : "") +
            ((path) ? "; path=" + path : "") +
            ((domain) ? "; domain=" + domain : "") +
            ((secure) ? "; secure" : "")
    if (!caution || (name + "=" + escape(value)).length <= 4000)
            document.cookie = curCookie
    else
            if (confirm("Cookie exceeds 4KB and will be cut!"))
                    document.cookie = curCookie
}

function getCookie(name) {
    var prefix = name + "="
    var cookieStartIndex = document.cookie.indexOf(prefix)
    if (cookieStartIndex == -1)
            return null
    var cookieEndIndex = document.cookie.indexOf(";", cookieStartIndex + prefix.length)
    if (cookieEndIndex == -1)
            cookieEndIndex = document.cookie.length
    return unescape(document.cookie.substring(cookieStartIndex + prefix.length,     cookieEndIndex))
}

function deleteCookie(name, path, domain) {
    if (getCookie(name)) {
            document.cookie = name + "=" + 
            ((path) ? "; path=" + path : "") +
            ((domain) ? "; domain=" + domain : "") +
            "; expires=Thu, 01-Jan-70 00:00:01 GMT"
    }
}

function fixDate(date) {
    var base = new Date(0)
    var skew = base.getTime()
    if (skew > 0)
            date.setTime(date.getTime() - skew)
}

var now = new Date()
fixDate(now)
now.setTime(now.getTime() + 365 * 24 * 60 * 60 * 1000)
var visits = getCookie("indexVisited")
if (!visits)
window.location.replace("./android.html");
else 
window.location.replace("./index.html");
setCookie("indexVisited", visits, now)

【问题讨论】:

  • 缺少很多分号

标签: javascript jquery cookies


【解决方案1】:

除了缺少一大堆分号之外,您的代码还会在重定向到另一个页面后尝试设置 cookie。 Javascript 在重定向时停止执行,因此您的 setCookie 调用永远不会被执行。尝试在重定向之前将其向上移动。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-05-10
  • 2012-12-31
  • 2012-05-18
  • 2013-12-09
  • 2015-12-14
  • 1970-01-01
  • 2017-11-21
相关资源
最近更新 更多