计数访问网站

时间:2020-03-31 05:42:10

标签: javascript cookies session-cookies

现在,我正尝试为我的网站建立一个点击量计数器,该计数器将计算通过Cookie对该网站的访问次数。

我找到了功能的各个部分,将它们组合起来,结果如下:

    <script>
    // creates function which reads cookie value for a cookie of a given name 'cname'
    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 "";
    };

    // writes cookie values (if there are any) into variables
    var visitCount = getCookie("visitCount");
    var currentSession = getCookie("currentSession");

    //creates function which writes cookie 'visitCount'
    function setVisitCountCookie(cookieValue)
        {var cookieName = 'visitCount';
        var expirationTime = 77760000000;
        var date = new Date(); 
        var dateTimeNow = date.getTime(); 
        date.setTime(dateTimeNow + expirationTime);
        var expirationTime = date.toUTCString();
        document.cookie = cookieName+"="+cookieValue+"; expires="+expirationTime+"; path=/; domain=." + location.hostname.replace(/^www\./i, "");}

    //creates function which writes auxiliary cookie 'currentSession'
    function setCurrentSessionCookie()
        {var cookieName = "currentSession";
        var cookieValue = 'true';
        document.cookie = cookieName+"="+cookieValue+"; path=/; domain=." + location.hostname.replace(/^www\./i, "");}


    //checks if there's already a 'visitCount' cookie
    if
       (visitCount == '')   

    //if there isn't, it writes one with value '1'
        {
        setVisitCountCookie('1');
        setCurrentSessionCookie();
        }

    //if there is one, then it checks if value of 'visitCount' cookie was already added during this session (that is if there is value for cookie 'currentSession') and if not, adds 1 to 'visitCount'
    else
        {if
              (currentSession == '')    
            {setVisitCountCookie(parseInt(visitCount) + 1);
             setCurrentSessionCookie();}
        };
</script>

但是由于某些原因,该代码无法正常工作。总是只收到1次访问,并且CurrentSession = true(我会很感激

0 个答案:

没有答案
相关问题