簡體   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