如何使用JavaScript计算我网站上的访问者数量?

时间:2015-07-24 12:50:11

标签: javascript web

我需要一个计数器来集成我的HTML代码,当访问者访问我的网页时,该代码从1到3。

例如,如果第一位访问者访问了我的页面,则计数为1,然后下一位访问者访问了计数为2的页面,第三位访问者计数为3,则第四位访问者再次从1开始,依此类推

2 个答案:

答案 0 :(得分:1)

您可以使用Cookie并简单地更新用户刷新时检测到的Cookie计数或使用计时器。一旦你有了cookie,你也可以做不同的事情。您也可以利用本地存储。

结帐 - http://samy.pl/evercookie/

<script type="text/javascript" src="evercookie.js"></script>

<script>
var ec = new evercookie(); 

// set a cookie "id" to "12345"
// usage: ec.set(key, value)
ec.set("id", "12345"); 

// retrieve a cookie called "id" (simply)
ec.get("id", function(value) { alert("Cookie value is " + value) }); 

// or use a more advanced callback function for getting our cookie
// the cookie value is the first param
// an object containing the different storage methods
// and returned cookie values is the second parameter
function getCookie(best_candidate, all_candidates)
{
    alert("The retrieved cookie is: " + best_candidate + "\n" +
        "You can see what each storage mechanism returned " +
        "by looping through the all_candidates object.");

    for (var item in all_candidates)
        document.write("Storage mechanism " + item +
            " returned: " + all_candidates[item] + "<br>");
}
ec.get("id", getCookie); 

// we look for "candidates" based off the number of "cookies" that
// come back matching since it's possible for mismatching cookies.
// the best candidate is most likely the correct one
</script> 

答案 1 :(得分:0)

如评论中所示,如果您只是寻找一些以相同概率加载随机页面的方法,而没有更复杂的服务器端代码,您可以这样做:

<script type="text/javascript">
    window.onload = function() {
        var numberOfPages = 3;
        var num = Math.round(Math.random() * numberOfPages);
        window.location.href = "/" + num + ".html";
    };    
</script>

当然,您会有0.html1.html2.html页面。这将以相同的概率随机加载这三个页面中的一个。它也可以扩展到您想要的任意数量的页面,只需添加更多页面并增加numberOfPages变量。如果您将此脚本放在网站的索引中,则此操作应该有效 - 页面的其余部分可以为空。