【问题标题】:Simple click counter with php and js使用 php 和 js 的简单点击计数器
【发布时间】:2014-07-22 11:23:04
【问题描述】:

尝试制作一个非常简单的计数器,每次用户单击链接时,它会将 mysql 数据库表中的值更新 1。

<a href='http://somesupersite.com' id='246' class='track'>My Link</a>

应该获取 id 并将其传递给 php 脚本的 javascript:

$(document).ready(function(){
$('a.track').click(function() {
$.post('http://mysupersite.com/sys/tracker.php', {id:this.id});
});
});

php 脚本 tracker.php 应该获取 post 变量并更新 mysql 数据库表列:

$id = $_POST['id'];
$con = mysqli_connect($mysqlHost, $mysqlUser, $mysqlPassword, $mysqlDatabase);
mysqli_query($con, "UPDATE table SET clicks = clicks + 1 WHERE id = $id");

我没有收到任何错误,但数据库也没有更新。

【问题讨论】:

  • Var_dump 您的查询并将其运行到Phpmyadmin
  • 你能回显UPDATE table SET clicks = clicks + 1 WHERE id = $id它打印的内容吗?
  • 将查询行替换为 mysqli_query($con, "UPDATE table SET clicks = clicks + 1 WHERE id = ".$id);

标签: php jquery mysql click counter


【解决方案1】:

我建议你这样做:

$(document).ready(function(){
    $('a.track').click(function(e) {
       e.preventDefault();
       $.post('http://mysupersite.com/sys/tracker.php', {id:this.id}, function(){
            window.location.href = e.target.getAttribute('href');
       });
    });
});

让您的链接从您的$.post() 的成功回调导航。


在我看来,当您单击锚点时,它只是导航到 href 提供的页面,所以这可能是 ajax 没有被调用。

【讨论】:

    【解决方案2】:

    在上下文中使用event.preventDefault()

    $(document).ready(function(){
       $('a.track').click(function(event) {
       event.preventDefault();
       $.post('http://mysupersite.com/sys/tracker.php', {id:this.id});
       });
    });
    

    【讨论】:

      【解决方案3】:

      试试这个:

      $(document).ready(function(){
          $('a.track').click(function() {
              console.log("here");
              $.post('http://mysupersite.com/sys/tracker.php', {id:this.id});
          });
      });
      

      当你点击a标签时,它会跳转到另一个页面。所以这个功能不能用。

      如果您在“此处”获取日志,它会起作用。

      【讨论】:

        猜你喜欢
        • 2011-11-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-11-14
        • 2017-01-07
        • 2018-12-30
        相关资源
        最近更新 更多