要用 html+javascript 实现智能温湿度监控,必须通过 fetch 定时调用 /api/sensor 接口获取动态数据,配合阈值判断、异常标红、离线提示及超时处理,否则仅为静态页面。

直接用 HTML + JavaScript 就能做出可实时刷新的温湿度监控页面,但真要“智能”——比如异常自动标红、历史趋势图、设备离线提示——光靠纯静态 HTML 不行,必须对接真实数据源(如 ESP32 上报的 API 或本地模拟接口),否则只是个好看摆设。
怎么让页面显示动态温湿度数值(非写死)
浏览器不能直接读取传感器硬件,必须通过 HTTP 请求获取数据。最轻量的做法是让后端(或 micro-HTTP 服务如 Flask/Node.js)暴露一个 /api/sensor 接口,返回 JSON:
{ "temperature": 26.4, "humidity": 62.1, "timestamp": "2024-05-22T14:30:12Z" }
前端用 fetch() 定时拉取:
setInterval(() => {
fetch('/api/sensor')
.then(r => r.json())
.then(data => {
document.getElementById('temp').textContent = data.temperature.toFixed(1);
document.getElementById('humi').textContent = data.humidity.toFixed(1);
});
}, 3000);
- 别用
XMLHttpRequest——fetch更简洁,现代浏览器全支持 - 务必加
.catch()处理请求失败(比如设备断网),否则页面卡住不报错 - 3 秒刷新是经验值:太短加重服务压力,太长(>10s)用户会觉得“不智能”
温度超限自动变色的 CSS + JS 联动逻辑
单纯用 CSS 的 :hover 或媒体查询没用,阈值判断必须在 JS 里做,再动态加 class:
function updateDisplay(data) {
const tempEl = document.getElementById('temp');
tempEl.textContent = data.temperature.toFixed(1);
// 清除旧状态
tempEl.classList.remove('warn-high', 'warn-low');
// 根据阈值加类
if (data.temperature > 35) tempEl.classList.add('warn-high');
if (data.temperature
<p>CSS 配合写死颜色即可:</p><div class="aritcle_card flexRow artxards">
<div class="artcardd flexRow">
<a class="aritcle_card_img" rel="nofollow" href="/xiazai/skill6712" title="Wechat HTML Publisher"><img
src="https://img.php.cn/upload/skill/000/000/081/179109368394970.jpg" alt="Wechat HTML Publisher" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a rel="nofollow" href="/xiazai/skill6712" title="Wechat HTML Publisher" class="overflowclass">Wechat HTML Publisher</a>
<p class="overflowclass">直接上传HTML富文本到微信公众号草稿箱。支持完整的HTML格式,无需Markdown转换。</p>
</div>
<a rel="nofollow" href="/xiazai/skill6712" title="Wechat HTML Publisher" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span>
</a>
</div>
</div>
<pre class="brush:php;toolbar:false;">.warn-high { color: #e74c3c; font-weight: bold; }
.warn-low { color: #3498db; font-weight: bold; }
- 阈值(如 35℃)别硬编码在 JS 里,建议从
data-threshold-high这类 HTML 属性读取,方便运维调整 - 别用
style.color = 'red'直接改内联样式——后续想统一换主题或加动画会非常难维护 - 湿度同理,但注意:60%–70% 是作物舒适区,不是越高越好,阈值逻辑要按农艺规则设
用 Chart.js 画 24 小时温湿度折线图(最小可行集成)
纯 HTML 表格或文字列表看不出趋势,“智能”体现在变化模式识别。Chart.js 是目前最省心的选择,CDN 引入即可:
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
初始化图表前,先用 JS 拉取历史数据(例如 /api/history?hours=24),格式需严格匹配 Chart.js 要求:
{
labels: ["00:00", "01:00", ..., "23:00"],
datasets: [{
label: '温度(℃)',
data: [24.1, 24.3, ..., 26.8],
borderColor: '#3498db',
tension: 0.3
}, {
label: '湿度(%)',
data: [65.2, 64.8, ..., 58.1],
borderColor: '#2ecc71',
tension: 0.3
}]
}
- 后端返回的时间字段必须转成 Chart.js 能识别的字符串(如
"2024-05-22T14:00:00"),别传时间戳数字——否则 X 轴乱序 - 数据点超过 200 个会明显卡顿,务必在后端做降采样(如每 10 分钟取均值),前端不做计算
- 移动端横屏查看图表时,记得加
responsive: true, maintainAspectRatio: false
设备离线时页面要有明确反馈,不能一直转圈
农业现场网络不稳定,fetch() 超时或 503 错误必须显性处理:
fetch('/api/sensor', { signal: AbortSignal.timeout(5000) })
.then(r => {
if (!r.ok) throw new Error(`HTTP ${r.status}`);
return r.json();
})
.then(updateDisplay)
.catch(err => {
document.getElementById('status').textContent = '设备离线';
document.getElementById('status').className = 'offline';
});
- 必须设
timeout,否则 Wi-Fi 断开时请求挂起几十秒,页面假死 -
status元素要放在显眼位置(比如标题旁),且用不同背景色+图标(可用 Unicode ✖️),不能只靠文字 - 别自动重试 100 次——改成“点击重试”按钮更可控,避免带宽被占满
真正卡住人的从来不是画个仪表盘,而是传感器数据格式不统一、HTTP 接口没鉴权被刷爆、或者温湿度单位混用(℃ 和 ℉ 同时出现)。上线前拿真实设备连 48 小时,盯着控制台看有没有 TypeError: Cannot read property 'temperature' of undefined——这种错误在测试页里永远复现不出来。
前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!










