Mayx的博客

Logo

Mayx's Home Page

View My GitHub Profile

About Me
22 June 2019 - 字数统计:2305 - 阅读大约需要7分钟 - Hits: Loading...

如何自己写一个博客计数器

by mayx


都怪LeanCloud,我得自己写计数器了!

事件起因

我之前用的博客计数器是用的LeanCloud作为后台制作的计数器,然后嘛……代码是抄的。结果最近LeanCloud凉了,这让我无法忍受,之前的代码我也看不懂,改也不会改……
那好吧,我只好自己写计数器了。
于是我花了很长时间,自己写了一个计数器,另外还得把原来的计数器信息转移过来……

使用方法

前端部分

主页显示点击数:

Hits: <span id="{{ post.url }}" class="visitors" >Loading...</span> 

内页显示点击数:

 Hits: <span id="{{ page.url }}" class="visitors" >Loading...</span> 

JS代码:(需要Jquery)

function showHitCount() {
    var visitors=$(".visitors");
    var i = 0;
    function showHitS() {
        $.get("https://计数器地址/counter.php?action=show&id="+visitors[i].id,function(data){
            visitors[i].innerHTML=Number(data);
            i++;
            if (i < visitors.length){
                showHitS();
            }
        });
    }
    showHitS();
}
function addCount() {
var visitors=$(".visitors");
    $.get("https://计数器地址/counter.php?action=add&id="+visitors[0].id,function(data){
        visitors[0].innerHTML=Number(data);
    });
}
$(function (){
    if (window.location.pathname !== '/' && $('.visitors').length == 1) {
        // in post.html, so add 1 to hit counts
        addCount();
    } else if ($('.post-link').length > 0){
        // in index.html, there are many 'visitors' and 'post-link', so just show hit counts.
        showHitCount();
    }
});

后端部分

MySQL建表:

CREATE TABLE `counter` (
  `url` char(50) NOT NULL,
  `counter` int(11) NOT NULL,
  UNIQUE KEY `url` (`url`)
);

PHP:

<?php
header('Access-Control-Allow-Origin: *');
$con=mysqli_connect("MySQL地址","用户名","密码","数据库名"); 
if (mysqli_connect_errno($con)) 
{ 
    die("连接 MySQL 失败: " . mysqli_connect_error()); 
}

$hid = md5($_GET[id]);

if ( $_GET[action] == "show" ) {

$sql = "SELECT * FROM `counter` WHERE `url` = '".$hid."' ";
$result = $con->query($sql);

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo $row["counter"];
}
} else {

$sql = "INSERT INTO `counter` (`url`, `counter`)
VALUES ('".$hid."', '0')";
 
if ($con->query($sql) === TRUE) {
    echo "0";
}else{
echo "Error";
}

}

} elseif ( $_GET[action] == "add" ) {


$sql = "SELECT * FROM `counter` WHERE `url` = '".$hid."' ";
$result = $con->query($sql);
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
$sql = "UPDATE `counter` SET `counter` = '".($row["counter"]+1)."' WHERE `url` = '".$hid."'";
$con->query($sql);
        echo ($row["counter"]+1);
}
} else {

$sql = "INSERT INTO `counter` (`url`, `counter`)
VALUES ('".$hid."', '1')";
 
if ($con->query($sql) === TRUE) {
    echo "1";
}else{
echo "Error";
}

}


} else {
header("HTTP/1.1 301 Moved Permanently");
header("Location: https://mabbs.github.io");
}
mysqli_close($con);

结果

看来还是自己写代码放心,至少服务是自己维护的,不像垃圾LeanCloud坏掉之后我就无能为力了……
不过说实话我根本不会JS(虽然我之前说我学这个),编写之中遇到了不少问题,所以在此感谢各位帮助我的各位大佬们,让我最终完成了这个计数器。

tags: 计数器
召唤伊斯特瓦尔