summary refs log tree commit diff
path: root/_posts/2019-06-22-counter.md
blob: 24e19c6ea014244fe3643a146ee21cdff9438f20 (plain)
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
---
layout: post
title: 如何自己写一个博客计数器
tags: [计数器]
---

  都怪LeanCloud,我得自己写计数器了!<!--more-->   
  
# 事件起因
  我之前用的博客计数器是用的LeanCloud作为后台制作的计数器,然后嘛……代码是抄的。结果最近[LeanCloud凉了](https://blog.avoscloud.com/6841/),这让我无法忍受,之前的代码我也看不懂,改也不会改……   
  那好吧,我只好自己写计数器了。   
  于是我花了很长时间,自己写了一个计数器,另外还得把原来的计数器信息转移过来……
  
# 使用方法
## 前端部分
  主页显示点击数:
```html
{% raw %}Hits: <span id="{{ post.url }}" class="visitors-index" >Loading...</span>{% endraw %} 
```
  内页显示点击数:
```html
{% raw %} Hits: <span id="{{ page.url }}" class="visitors" >Loading...</span>{% endraw %} 
```
  JS代码:(需要Jquery)
```js
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建表:
```sql
CREATE TABLE `counter` (
  `url` char(50) NOT NULL,
  `counter` int(11) NOT NULL,
  UNIQUE KEY `url` (`url`)
);
```

  PHP:
```php
<?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;
```
  2022.07.26更新:之前的代码实在是太垃圾了,现在最起码PHP也会的差不多了,稍微优化一下。   

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