使用AJAX和PHP永久覆盖简单的点击次数

时间:2014-09-18 22:07:49

标签: javascript php jquery ajax

我正在编写一个网站,当任何用户点击按钮时,点击计数器会增加并显示。必须永久增加计数。我想象的解决方案将涉及JS和PHP之间的某种形式的交互。

我完全熟悉JavaScript和jQuery,远不如PHP。除了展示这个概念之外,fiddle here是无用的。每次加载页面时,它显然会刷新回0。我需要跟踪并保存当前的clickCounter“全球”,可以这么说。

var clickCounter = 0;

$(document).ready(function () {
    $("#displayClicks").html("<h1>" + clickCounter + "</h1>");
    $("#button").click(function () {
        clickCounter++;
        $("#displayClicks").html("<h1>" + clickCounter + "</h1>");
    });
});

2 个答案:

答案 0 :(得分:2)

为了让计数器显示永久值,您必须将值存储在静态文件或数据库中。

静态文件方法

当用户导航到计数器页面时,您将需要对PHP脚本进行AJAX调用,以获取当前计数器编号。

如果您使用静态文件来存储您的计数器编号,您只需向计数器文件发送一个请求以获取其内容,而不是延长该过程并使用PHP脚本执行此操作。

获得计数器值

JavaScript的:

var counterValue = 0;

$(document).ready(function () {
    $.ajax({
        url: "Counter.txt",
        async: false,
        success: function (data){
            // This is assuming that Counter.txt's value will always be a number.
            counterValue = parseInt(data);
        }
    });
    $("#clickCount").html("<h1>" + counterValue + "</h1>");
    $("#clickThis").click(function () {
        $.ajax({
            url: "addcounter.php",
            success: function (){counterValue++;}
        });
        $("#clickCount").html("<h1>" + counterValue + "</h1>");
    });
});

Counter.txt的内容可能只是42

设置计数器值

PHP(addcounter.php):     

$counterFile = "Counter.txt";
#               ^ the file we need to open is Counter.txt

$fileRW = fopen($counterFile, 'a');
#         ^ open the file

$fileContents = fread($fileRW, filesize($counterFile));
#               ^ get the contents of the file,
#                 so we know what to add to

$counterValue = intval($fileContents);

fclose($fileRW);
# ^ we close the file here so we can open again with the the 'w' mode,
#   which will truncate the file so we can rewrite its contents

$fileRW = fopen($counterFile, 'w');

fwrite($fileRW, $counterValue);
fclose($fileRW);
# ^ write to file and close

数据库方法

如果您选择使用此方法,则必须使用PHP脚本来获取设置计数器值。

获得计数器值

JavaScript的:

var counterValue = 0;

$(document).ready(function () {
    $.ajax({
        url: "getcounter.php",
        async: false,
        success: function (data){
            // getcounter.php should always return a single number.
            counterValue = parseInt(data);
        }
    });
    $("#clickCount").html("<h1>" + counterValue + "</h1>");
    $("#clickThis").click(function () {
        $.ajax({
            url: "addcounter.php",
            success: function (){counterValue++;}
        });
        $("#clickCount").html("<h1>" + counterValue + "</h1>");
    });
});

PHP(getcounter.php):     

$db_user        = "example";
#                 ^ replace with database login username

$db_pass        = "example";
#                 ^ replace with database login password

$db_info        = "mysql:host=localhost;dbname=example";
#               replace with: ^ host           ^ database name

$PDO = new PDO($db_info, $db_user, $db_pass);
#          ^ creates a connection to the MySQL database

$SQLQuery = "SELECT `counter` FROM `Counter`";
#                   ^ counter column      ^ counter table 

$Statement = $PDO->prepare($SQLQuery);
#                  ^ prepares a statement object from the query string
$Statement->execute();
$CounterData = $Statement->fetch();
#                          ^ fetches the info for the counter column in the Counter table

echo $CounterData['counter'];
#    ^ echo the counter value for the AJAX request

设置计数器值

PHP(addcounter.php):     

$db_user        = "example";
#                 ^ replace with database login username

$db_pass        = "example";
#                 ^ replace with database login password

$db_info        = "mysql:host=localhost;dbname=example";
#               replace with: ^ host           ^ database name

$PDO = new PDO($db_info, $db_user, $db_pass);
#          ^ creates a connection to the MySQL database

$SQLQuery = "UPDATE `Counter` SET `counter`=`counter`+1";
#                   ^ counter table     ^ set counter column to current value plus one 

$Statement = $PDO->prepare($SQLQuery);
#                  ^ prepares a statement object from the query string
$Statement->execute();

我对AJAX&amp; amp;的知识JS有点生疏,请原谅任何错误;这篇文章的目的是总结所涉及的代码,并不是真正意义上的复制/粘贴。

答案 1 :(得分:0)

使用Redis数据库或Memcached取决于您需要存储该值的时间。 每次单击该按钮,您都会向服务器发送ajax请求并递增密钥。