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 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程