
本文介绍如何将 php 查询的题库数据转为 json 供前端使用,并通过 javascript 实现自动倒计时、按时间间隔逐条显示记录集,支持无缝切换与边界控制。
本文介绍如何将 php 查询的题库数据转为 json 供前端使用,并通过 javascript 实现自动倒计时、按时间间隔逐条显示记录集,支持无缝切换与边界控制。
在构建在线测验、答题系统或轮播式内容展示页时,常需按固定时间(如每题 10 秒)自动切换题目,并在倒计时归零时跳转至下一条记录。直接在 PHP 中一次性渲染全部 首先,PHP 端不再循环输出 HTML,而是将查询结果统一编码为 JSON,并内联注入到页面脚本中: ⚠️ 注意:确保字段名(如 HTML 仅保留一个干净的容器,所有内容由 JS 动态写入: 配合基础样式(适配全屏与隐藏溢出): JavaScript 使用立即执行函数封装倒计时逻辑,维护当前索引 页面加载后,首题立即显示并开始倒计时;归零后自动刷新内容为下一题,倒计时重置为该题设定时长;全部题展示完毕后显示完成提示。整个过程平滑、可控、无闪烁,符合现代单页交互体验标准。✅ 推荐方案:PHP 输出 JSON + JS 定时器驱动
<?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>
no, question, time)与数据库实际列名一致;若含中文或特殊字符,JSON_UNESCAPED_UNICODE 可避免乱码。? 前端结构:单容器 + 动态内容填充
<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; }
⏱️ 核心逻辑:递归定时器 + 状态管理
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 = QUESTION_SET.length) {
// 全部完成
numberEl.textContent = '✅';
textEl.textContent = '全部完成!';
timerEl.textContent = '';
return;
}
// 重置倒计时并渲染新题
remainingTime = QUESTION_SET[currentIndex].time;
renderQuestion(currentIndex);
startCountdown(); // 重启定时器
}
}, 1000);
}
startCountdown();
});
? 关键设计说明
currentIndex >= QUESTION_SET.length)防止越界;clearInterval 显式清理旧定时器,避免内存泄漏;✅ 最终效果
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











