<?php
// counter.php
$file = 'count.txt';
$count = file_exists($file) ? (int)file_get_contents($file) : 0;
$count++;
file_put_contents($file, $count);
header('Content-Type: application/javascript; charset=utf-8');
echo "document.getElementById('counter').textContent = {$count};";
?>
缺點明顯:耦合度高、難以除錯、無法複用邏輯、安全風險(XSS)、不支援現代模組化開發。
<?php
// api/counter.php
header('Content-Type: application/json; charset=utf-8');
$file = __DIR__ . '/../data/count.txt';
$count = file_exists($file) ? (int)file_get_contents($file) : 0;
$count++;
file_put_contents($file, $count);
echo json_encode(['count' => $count, 'updated_at' => date('c')]);
<div id="counter">載入中...</div>
<script type="module">
async function loadCounter() {
try {
const res = await fetch('/api/counter.php');
const data = await res.json();
document.getElementById('counter').textContent = data.count;
} catch (e) {
console.error('計數器載入失敗', e);
}
}
loadCounter();
</script>