dpswo40440 2015-12-10 15:41
浏览 95
已采纳

在cookie中存储jQuery点击计数,然后回显它。

I'm trying to use jQuery to count clicks, store them in a cookie and then echo them back out.

I've found some code online that allows me to do it, but I dont seem to be able to make it work. It's creating the cookie file and storing '0' in it, but it does not update on clicking of links. Any guidance as to whats going wrong with this code would be great. :

clickCount.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>
  • 写回答

1条回答 默认 最新

  • douou0977 2015-12-10 15:54
    关注

    In you PHP code, you're not storing the click count into a cookie, but into a file.

    You either have to update the counter file by by making an AJAX request from your JavaScript to your server, or actually write a cookie within your PHP file:

    <?php
    
    $cookieName = 'linkcounter';
    
    $count = isset($_COOKIE[$cookieName]) ? (int)$_COOKIE[$cookieName] : 0;
    $count++;
    
    setcookie($cookieName, $count);
    
    ?>
    
    Link clicks: <?=$count?>
    

    Make sure you use the same cookie name in both JavaScript and PHP.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题