JavaScript链接点击计数器

时间:2010-06-25 01:19:13

标签: javascript click-counting

我需要一个脚本来计算我网站上的链接点击次数,并将报告计数到flatfile / excel。

1 个答案:

答案 0 :(得分:1)

在这种情况下,使用像jQuery这样的Javascript框架是明智的。

请注意,您无法将数据保存到客户端计算机上的文件中。相反,您可以对服务器执行AJAX,并通过服务器上的SSI将其保存到数据库/ excel / file中,无论数据存储是什么。

我的演示将使用jQueryjQuery Cookie PluginPHP

countdetect.js

jQuery(function(){
  $("a").click(function{
    var cookiename = 'linkcounter';
    if($.cookie(cookiename) == null){
       $.cookie(cookiename, 0);
    }
    $.cookie(cookiename, $.cookie(cookiename)+1);
  });
});

的index.php

<?php

session_start();

$counter_file = 'counter';
if(!file_exists($counter_file)){
  file_put_contents($counter_file, 0);
}

$counts = (int)file_get_contents($counter_file);
file_put_contents($counter_file, $counts++);
// you can use $counts if you want to display it on the page.

?><!DOCTYPE html>
<html>
  <head>
    <title>Link Click Counter Test</title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
    <script type="text/javascript" src="jquery.cookie.js"></script>
    <script type="text/javascript" src="countdetect.js"></script>
  </head>
  <body>
    <a href="http://www.google.com/"></a><br />
    <a href="<?php echo $_SERVER['PHP_SELF']; ?>"></a><br />
    Link clicks: <?php echo $counts; ?>
  </body>
</html>