重定向cookie卡在循环中

时间:2012-02-06 16:59:21

标签: javascript jquery cookies

由于某种原因,这个脚本陷入重定向循环,不会让你离开" android.html"。网址栏显示它正在尝试转到" 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)

1 个答案:

答案 0 :(得分:0)

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