Mayx's Home Page https://mabbs.github.io
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

92 lines
3.1 KiB

  1. ---
  2. layout: post
  3. title: 如何自己写一个博客计数器
  4. tags: [计数器]
  5. ---
  6. 都怪LeanCloud,我得自己写计数器了!<!--more-->
  7. # 事件起因
  8. 我之前用的博客计数器是用的LeanCloud作为后台制作的计数器,然后嘛……代码是抄的。结果最近[LeanCloud凉了](https://blog.avoscloud.com/6841/),这让我无法忍受,之前的代码我也看不懂,改也不会改……
  9. 那好吧,我只好自己写计数器了。
  10. 于是我花了很长时间,自己写了一个计数器,另外还得把原来的计数器信息转移过来……
  11. # 使用方法
  12. ## 前端部分
  13. 主页显示点击数:
  14. ```html
  15. {% raw %}Hits: <span id="{{ post.url }}" class="visitors-index" >Loading...</span>{% endraw %}
  16. ```
  17. 内页显示点击数:
  18. ```html
  19. {% raw %} Hits: <span id="{{ page.url }}" class="visitors" >Loading...</span>{% endraw %}
  20. ```
  21. JS代码:(需要Jquery)
  22. ```js
  23. var auxiliaryHost = "你的域名";
  24. function showHitS(hits){
  25. $.get(auxiliaryHost+"/counter.php?action=show&id="+hits.id,function(data){
  26. hits.innerHTML=Number(data);
  27. });
  28. }
  29. function showHitCount() {
  30. var visitors=$(".visitors-index");
  31. for(var i = 0; i < visitors.length; i++){
  32. showHitS(visitors[i]);
  33. }
  34. }
  35. function addCount() {
  36. var visitors=$(".visitors");
  37. $.get(auxiliaryHost+"/counter.php?action=add&id="+visitors[0].id,function(data){
  38. visitors[0].innerHTML=Number(data);
  39. });
  40. }
  41. if ($('.visitors').length == 1) {
  42. addCount();
  43. } else if ($('.visitors-index').length > 0){
  44. showHitCount();
  45. }
  46. ```
  47. 2021.03.23更新:修复了一些BUG并且支持异步了
  48. ## 后端部分
  49. MySQL建表:
  50. ```sql
  51. CREATE TABLE `counter` (
  52. `url` char(50) NOT NULL,
  53. `counter` int(11) NOT NULL,
  54. UNIQUE KEY `url` (`url`)
  55. );
  56. ```
  57. PHP:
  58. ```php
  59. <?php
  60. header('Access-Control-Allow-Origin: *');
  61. $db = new PDO("mysql:host=MySQL地址;dbname=数据库名", "用户名", "密码", array(PDO::ATTR_PERSISTENT => true));
  62. if (isset($_GET['id'])){
  63. $hid = (string)md5($_GET['id']);
  64. } else {
  65. header("HTTP/1.1 301 Moved Permanently");
  66. header("Location: https://mabbs.github.io");
  67. exit(0);
  68. }
  69. $select = $db->prepare("SELECT IFNULL((SELECT `counter` FROM `counter` WHERE `url` = ?), 0) count");
  70. $select->execute(array($hid));
  71. $counter = $select->fetch(PDO::FETCH_ASSOC)['count'];
  72. if (isset($_GET['action'])){
  73. if ($_GET['action'] == "add") {
  74. $counter = $counter + 1;
  75. $insert = $db->prepare("INSERT INTO `counter` (`url`, `counter`) VALUES (?, ?) ON DUPLICATE KEY UPDATE `counter` = ?");
  76. $insert->execute(array($hid, $counter, $counter));
  77. }
  78. }
  79. echo $counter;
  80. ```
  81. 2022.07.26更新:之前的代码实在是太垃圾了,现在最起码PHP也会的差不多了,稍微优化一下。
  82. # 结果
  83. 看来还是自己写代码放心,至少服务是自己维护的,不像垃圾LeanCloud坏掉之后我就无能为力了……
  84. 不过说实话我根本不会JS(虽然我之前说我学这个),编写之中遇到了不少问题,所以在此感谢各位帮助我的各位大佬们,让我最终完成了这个计数器。

Powered by TurnKey Linux.