You need to enable JavaScript to run this app. ESP32使用Ajax GET获取多变量值并无刷新更新网页的实现咨询
优惠活动
大模型
产品
解决方案
定价
更多

ESP32使用Ajax GET获取多变量值并无刷新更新网页的实现咨询

ESP32多变量Ajax无刷新更新实现方案

第一步:修改ESP32服务端接口,返回JSON格式数据

原有接口仅返回单个变量的纯文本值,调整为返回JSON格式的多变量集合,需要先安装ArduinoJson库用于JSON构造。
示例服务端代码(基于WebServer库):

#include <ArduinoJson.h>

// 原有readADC接口的处理函数修改为如下逻辑
void handleReadSensor() {
  // 采集所有需要上报的变量,可根据需求增删
  int adcVal = analogRead(34);
  float temperature = dht.readTemperature();
  float humidity = dht.readHumidity();
  int wifiRssi = WiFi.RSSI();

  // 构造JSON对象
  StaticJsonDocument<256> doc;
  doc["adc"] = adcVal;
  doc["temp"] = temperature;
  doc["humi"] = humidity;
  doc["rssi"] = wifiRssi;

  // 设置响应头为JSON格式,返回数据
  server.send(200, "application/json", doc.as<String>());
}

第二步:前端HTML新增对应展示节点

给每个需要展示的变量准备对应ID的DOM容器,示例:

<div class="sensor-card">
  <p>ADC采集值:<span id="ADCValue"></span></p>
  <p>环境温度:<span id="tempValue"></span> ℃</p>
  <p>环境湿度:<span id="humiValue"></span> %RH</p>
  <p>WiFi信号强度:<span id="rssiValue"></span> dBm</p>
</div>

第三步:修改Ajax请求逻辑,解析JSON批量更新数据

调整原有getData函数,将接口返回的JSON字符串解析为JS对象后,分别赋值给对应DOM节点:

setInterval(function() {
  getData();
}, 500);

function getData() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      try {
        // 解析返回的JSON数据
        const sensorData = JSON.parse(this.responseText);
        // 批量更新对应DOM节点
        document.getElementById("ADCValue").textContent = sensorData.adc;
        document.getElementById("tempValue").textContent = sensorData.temp.toFixed(1); // 保留1位小数
        document.getElementById("humiValue").textContent = sensorData.humi.toFixed(1);
        document.getElementById("rssiValue").textContent = sensorData.rssi;
      } catch (err) {
        // 数据解析异常时的容错处理,可根据需求调整
        console.log("数据解析失败", err);
      }
    }
  };
  xhttp.open("GET", "readADC", true);
  xhttp.send();
}

如果后续需要新增变量,仅需在服务端JSON中新增对应字段,前端新增对应DOM节点和赋值逻辑即可,无需调整请求逻辑。

内容的提问来源于stack exchange,提问作者sharkyenergy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.16 05:45:00