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

前端部分
主页显示点击数:

1
2
3

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

内页显示点击数:

1
2
3

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

JS代码:(需要Jquery)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

var auxiliaryHost = "你的域名";
function showHitS(hits){
$.get(auxiliaryHost+"/counter.php?action=show&id="+hits.id,function(data){
hits.innerHTML=Number(data);
});
}
function showHitCount() {
var visitors=$(".visitors-index");
for(var i = 0; i < visitors.length; i++){
showHitS(visitors[i]);
}

}
function addCount() {
var visitors=$(".visitors");
$.get(auxiliaryHost+"/counter.php?action=add&id="+visitors[0].id,function(data){
visitors[0].innerHTML=Number(data);
});
}
if ($('.visitors').length == 1) {
addCount();
} else if ($('.visitors-index').length > 0){
showHitCount();
}

2021.03.23更新:修复了一些BUG并且支持异步了

后端部分

MySQL建表:

1
2
3
4
5
6
7

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

PHP:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

<?php
header('Access-Control-Allow-Origin: *');
$db = new PDO("mysql:host=MySQL地址;dbname=数据库名", "用户名", "密码", array(PDO::ATTR_PERSISTENT => true));

if (isset($_GET['id'])){
$hid = (string)md5($_GET['id']);
} else {
header("HTTP/1.1 301 Moved Permanently");
header("Location: https://mabbs.github.io");
exit(0);
}
$select = $db->prepare("SELECT IFNULL((SELECT `counter` FROM `counter` WHERE `url` = ?), 0) count");
$select->execute(array($hid));
$counter = $select->fetch(PDO::FETCH_ASSOC)['count'];
if (isset($_GET['action'])){
if ($_GET['action'] == "add") {
$counter = $counter + 1;
$insert = $db->prepare("INSERT INTO `counter` (`url`, `counter`) VALUES (?, ?) ON DUPLICATE KEY UPDATE `counter` = ?");
$insert->execute(array($hid, $counter, $counter));
}
}
echo $counter;