doulin2947 2019-03-17 12:34
浏览 94
已采纳

对链接上的计数点击进行ajax查询

I must count clicks on link and pass result to php-file.I think that it do by dint of ajax-query.

<a class='link' href='www.site.com'>Open</a>

<script>
var count=0;
$('.link').on('click',function(){
count+=1;
});
</script>

What must I do next? How can I pass count to array POST or Get?

  • 写回答

2条回答 默认 最新

  • duanpang1987 2019-03-17 13:30
    关注

    If you want to count clicks on some link, then you have to use file or database to save the value, because PHP does not save the state.

    Here I am giving an example of using a database for this:

    The Ajax

    $('.link').on('click',function(){
      $.ajax({
          url:"<?php echo 'Your url to incrementCount() method';?>",
          method:"POST",
          data:{},
          success:function(response){
              // on success do something
          }                    
      });
    });
    

    The PHP method

    public function incrementCount(){
      $UpdateQuery = "UPDATE link_counts SET link_count=link_count + 1 WHERE id=1";
      // here 'link_counts' is table name and 'link_count' is the column name to update
      $result = mysql_query($UpdateQuery );
    }
    

    The 'link_counts' table

    -------+------------+
    |  id  | link_count |
    -------+------------+
    

    Here link_count column value is 0 by default. By this, you can update the field on the occurrence of click event of .link class.

    Alternatively, you can use user_id to count which user clicked the .link class. To achieve this you need to add some where condition to the update query.

    If you want to do this with a file, then change the PHP method by below code-

    PHP Method for file handling

    $file = 'link_counter.txt';
    
    // default the counter value to 1
    $counter = 1;
    
    // add the previous counter value if the file exists    
    if (file_exists($file)) {
        $counter += file_get_contents($file);
    }
    
    // write the new counter value to the file
    file_put_contents($file, $counter);
    

    Hope this helps.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)