用PHP+JS实现按日期自动更新 index.html 的正确姿势
背景需求
在 index.html 中放一个 <div id="YYYY-MM-DD"></div>,访问时用 JS 判断这个 div 的 id 是否等于今天的日期:
- 一致:什么都不做
-
不一致:请求
index.php?debug=1让后端重新生成index.html,然后刷新页面
看起来很简单,但实际落地时会踩到两个坑:无限刷新 和 前后端日期格式不匹配。下面分别说明。
一、核心逻辑
前端 JS 负责两件事:生成今日日期字符串、查找对应 id 的 div。
function getTodayDateString() {
const d = new Date();
return d.getFullYear() + '-' +
String(d.getMonth() + 1).padStart(2, '0') + '-' +
String(d.getDate()).padStart(2, '0');
}
const today = getTodayDateString();
const dateDiv = document.getElementById(today);
if (!dateDiv) {
fetch('index.php?debug=1', { cache: 'no-store' })
.then(() => window.location.reload(true));
}
注意这里用 padStart(2, '0') 保证输出 2026-11-19、2026-01-05 这种补零格式。这一点直接关系到第二个坑。
二、坑一:无限刷新
如果 index.php?debug=1 没成功生成包含今日 id 的 index.html(比如生成失败、内容不对、请求返回 500),刷新后脚本再次执行 → 依然找不到 div → 再次请求 → 再次刷新,进入死循环。
触发场景包括:
- 后端生成失败(权限、路径、逻辑错误)
- 生成的 HTML 里根本没输出约定的 div
-
网络请求失败,但
catch里也调用了reload - 浏览器缓存导致读到旧文件
解决思路:给刷新加一次性保护。 用 sessionStorage 标记“已尝试过”,最多刷新一次:
if (sessionStorage.getItem('date_fix_attempted') === '1') {
console.error('已尝试更新仍未匹配,停止刷新以避免死循环');
return;
}
sessionStorage.setItem('date_fix_attempted', '1');
fetch('index.php?debug=1', { cache: 'no-store' })
.then(() => window.location.reload(true))
.catch(() => {
// 失败不刷新,并清除标记便于下次重试
sessionStorage.removeItem('date_fix_attempted');
});
这样即使后端出问题,也只会刷新一次,不会卡死浏览器。
三、坑二:PHP 的 n/j 不补零
后端生成日期时,很多人会写:
$now = new DateTime();
$month = $now->format('n'); // 不补零
$day = $now->format('j'); // 不补零
$fullDate = "{$year}年{$month}月{$day}日";
n 和 j 是无前导零格式,1 月 5 日会输出 2026年1月5日,而前端 JS 生成的是 2026-01-05。两者格式完全不同,id 永远对不上 → 每次访问都判定“不一致” → 每次都触发刷新。
PHP 日期格式符对比:
| 格式符 | 含义 | 11月19日 | 是否补零 |
|---|---|---|---|
n
|
月份 |
11 / 1
|
❌ |
m
|
月份 |
11 / 01
|
✅ |
j
|
日期 |
19 / 5
|
❌ |
d
|
日期 |
19 / 05
|
✅ |
正确做法:两端统一用 YYYY-MM-DD 补零格式。
PHP 端:
$idDate = (new DateTime())->format('Y-m-d');
// 输出:<div id="<?= $idDate ?>"></div>
前端已用 padStart 生成同格式,两端即可匹配。
四、一个隐藏的时区细节
JS 如果图省事用 new Date().toISOString().slice(0, 10),拿到的是 UTC 日期。在东八区,凌晨 0–8 点访问会取到前一天,导致与后端本地日期不一致,同样触发误刷新。
稳妥写法仍是本地时间手工拼接:
const d = new Date();
const today = d.getFullYear() + '-' +
String(d.getMonth() + 1).padStart(2, '0') + '-' +
String(d.getDate()).padStart(2, '0');
五、最终推荐实现
(function () {
function getTodayDateString() {
const d = new Date();
return d.getFullYear() + '-' +
String(d.getMonth() + 1).padStart(2, '0') + '-' +
String(d.getDate()).padStart(2, '0');
}
const today = getTodayDateString();
if (document.getElementById(today)) {
sessionStorage.removeItem('date_fix_attempted');
return; // 一致,不处理
}
if (sessionStorage.getItem('date_fix_attempted') === '1') {
console.error('更新后仍未匹配,停止刷新以避免死循环');
return;
}
sessionStorage.setItem('date_fix_attempted', '1');
fetch('index.php?debug=1', {
method: 'GET',
cache: 'no-store',
headers: { 'Pragma': 'no-cache', 'Cache-Control': 'no-cache' }
})
.then(function () { window.location.reload(true); })
.catch(function (err) {
console.error('请求失败:', err);
sessionStorage.removeItem('date_fix_attempted'); // 失败不刷新,下次可重试
});
})();
六、要点总结
-
防死循环:用
sessionStorage做一次性标记,失败时不刷新。 -
格式统一:PHP 用
Y-m-d(m/d补零),JS 用padStart补零,避免n/j造成 id 不匹配。 -
时区安全:JS 用本地时间拼字符串,别用
toISOString()取日期。 -
根因解决:确保
index.php?debug=1确实生成包含今日 id 的index.html,这比前端任何补救都重要。
按这几点处理后,这个看似简单的“按日期自动更新”功能就能稳定运行,不会出现循环刷新或永远不更新的问题。
- 上一篇:MyBatis-Plus 条件构造sql指南:常用条件与 and/or 逻辑嵌套
- 下一篇:无