
本文介绍如何将 php 查询的题库数据转为 json 供前端使用,并通过 javascript 实现自动倒计时、按时间间隔逐条显示记录集,支持无缝切换与边界控制。
本文介绍如何将 php 查询的题库数据转为 json 供前端使用,并通过 javascript 实现自动倒计时、按时间间隔逐条显示记录集,支持无缝切换与边界控制。
在构建在线测验、答题系统或轮播式内容展示页时,常需按固定时间(如每题 10 秒)自动切换题目,并在倒计时归零时跳转至下一条记录。直接在 PHP 中一次性渲染全部 <div class="area"> 会导致 DOM 膨胀、难以动态控制,且无法实现“仅显示当前题”的交互逻辑。更优解是:<strong>服务端提供结构化数据,前端用 JavaScript 驱动状态流转</strong>。<h3>✅ 推荐方案:PHP 输出 JSON + JS 定时器驱动</h3>
<p>首先,PHP 端不再循环输出 HTML,而是将查询结果统一编码为 JSON,并内联注入到页面脚本中:</p><pre class="brush:php;toolbar:false;"><?php
$mysqli = new mysqli("localhost", "root", "", "learningbydoing");
$result = $mysqli->query("SELECT `no`, `question`, `time` FROM question");
$records = $result->fetch_all(MYSQLI_ASSOC);
$json = json_encode($records, JSON_UNESCAPED_UNICODE);
?>
<script>
const QUESTION_SET = <?= $json ?>;
</script></pre><blockquote><p>⚠️ 注意:确保字段名(如 <code>no, question, time)与数据库实际列名一致;若含中文或特殊字符,JSON_UNESCAPED_UNICODE 可避免乱码。
? 前端结构:单容器 + 动态内容填充
HTML 仅保留一个干净的容器,所有内容由 JS 动态写入:
立即学习“Java免费学习笔记(深入)”;
<div class="area" style="height:100vh; overflow:hidden;">
<div class="boxquestion">
<label id="q-number"></label><br>
<label id="q-text"></label><br>
<label id="countdowntimer"></label><br>
</div>
</div>配合基础样式(适配全屏与隐藏溢出):
.area {
height: 100vh;
width: 100%;
overflow: hidden;
}
.boxquestion {
padding: 2rem;
text-align: center;
}
#q-number { color: #fff; background: #28a745; padding: 0.5rem 1rem; border-radius: 4px; }
#q-text { font-size: 1.4rem; color: #007bff; margin: 1rem 0; }
#countdowntimer { color: #fff; background: #dc3545; padding: 0.5rem 1rem; border-radius: 4px; font-weight: bold; }⏱️ 核心逻辑:递归定时器 + 状态管理
JavaScript 使用立即执行函数封装倒计时逻辑,维护当前索引 currentIndex 和剩余时间 remainingTime:
document.addEventListener('DOMContentLoaded', () => {
const numberEl = document.getElementById('q-number');
const textEl = document.getElementById('q-text');
const timerEl = document.getElementById('countdowntimer');
if (!QUESTION_SET || QUESTION_SET.length === 0) {
numberEl.textContent = '—';
textEl.textContent = '暂无题目';
timerEl.textContent = '—';
return;
}
let currentIndex = 0;
let remainingTime = QUESTION_SET[0].time;
// 初始化首题
renderQuestion(currentIndex);
function renderQuestion(index) {
const q = QUESTION_SET[index];
numberEl.textContent = q.no || q.id || '#';
textEl.textContent = q.question || '未知题目';
timerEl.textContent = remainingTime;
}
// 倒计时主循环
function startCountdown() {
const timer = setInterval(() => {
remainingTime--;
if (remainingTime >= 0) {
timerEl.textContent = remainingTime;
}
if (remainingTime <= 0) {
clearInterval(timer);
// 切换到下一题
currentIndex++;
if (currentIndex >= QUESTION_SET.length) {
// 全部完成
numberEl.textContent = '✅';
textEl.textContent = '全部完成!';
timerEl.textContent = '';
return;
}
// 重置倒计时并渲染新题
remainingTime = QUESTION_SET[currentIndex].time;
renderQuestion(currentIndex);
startCountdown(); // 重启定时器
}
}, 1000);
}
startCountdown();
});? 关键设计说明
- 解耦渲染与数据:PHP 只负责数据供给,JS 全权控制 UI 流程,便于后期扩展(如添加暂停/上一题/答案提交等);
- 内存友好:不预先生成所有 DOM 节点,仅维护当前题所需元素,适合大量题目场景;
-
健壮性处理:
- 空数据兜底提示;
- 边界检查(
currentIndex >= QUESTION_SET.length)防止越界; - 使用
clearInterval显式清理旧定时器,避免内存泄漏;
- 可扩展性强:后续可轻松接入音频提醒、自动保存作答、进度条可视化等。
✅ 最终效果
页面加载后,首题立即显示并开始倒计时;归零后自动刷新内容为下一题,倒计时重置为该题设定时长;全部题展示完毕后显示完成提示。整个过程平滑、可控、无闪烁,符合现代单页交互体验标准。


















