繁体   English   中英

使用PHP和JS的简单点击计数器

[英]Simple click counter with php and js

尝试制作一个非常简单的计数器,每次用户单击链接时,该计数器会将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");

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

我建议你这样做:

$(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。

尝试这个:

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

单击a标签时,它会跳到另一页。 因此此功能无法正常工作。

如果您获得日志“这里”,则它起作用。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM