小永高呐 发表于 2024-12-2 21:15:41

分享一个基于php+js的网页计数器吧

本帖最后由 小永高呐 于 2024-12-2 21:22 编辑

之前用的 busuanzi 的计数器,不过总是担心哪天突然挂了,索性考虑自建一个

在需要计数的网页引入如下js代码

<script>
fetch('/fwltj.php')
.then(response => response.json())
.then(data => {
document.getElementById('fwltj').innerText = data.visitCount;
})
.catch(error => console.error('0:', error));
</script>

<script>
fetch('/fwltj.php')
.then(response => response.json())
.then(data => {
document.getElementById('fwltj').innerText = data.visitCount;
})
.catch(error => console.error('0:', error));
</script>

在页面显示的地方使用如下代码来调用显示

<span id="fwltj"></span>

在主机新建一个叫 fwltj.php 的文件,粘贴如下代码

<?php
$visitCountFile = 'fwl.txt';
function getVisitCount() {
    global $visitCountFile;
    if (file_exists($visitCountFile)) {
      return file_get_contents($visitCountFile);
    }
    return 0;
}
function increaseVisitCount() {
    global $visitCountFile;
    $visitCount = getVisitCount();
    file_put_contents($visitCountFile, ++$visitCount);
}
increaseVisitCount();
header('Content-Type: application/json');
echo json_encode(['visitCount' => getVisitCount()]);
?>

<?php
$visitCountFile = 'fwl.txt';
function getVisitCount() {
    global $visitCountFile;
    if (file_exists($visitCountFile)) {
      return file_get_contents($visitCountFile);
    }
    return 0;
}
function increaseVisitCount() {
    global $visitCountFile;
    $visitCount = getVisitCount();
    file_put_contents($visitCountFile, ++$visitCount);
}
increaseVisitCount();
header('Content-Type: application/json');
echo json_encode(['visitCount' => getVisitCount()]);
?>

之后就能正常使用了
页: [1]
查看完整版本: 分享一个基于php+js的网页计数器吧