You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用innerHTML或createElement展示Axios请求返回的Payload?

解决方案:Axios调用API并渲染天气数据到页面

你在HTML内联脚本中用Axios调用天气API,需要用async/await处理请求结果,将成功数据传入setResults()渲染,错误传入setError()展示,同时纠结是否该用createElement,以及如何将JSON数据转为HTML。以下是具体实现方案:


一、完善API请求的结果与错误传递

首先在run()方法中,Axios的响应数据存在response.data中,直接传递给setResults();捕获错误时区分网络错误、API业务错误,生成友好提示传给setError():

async run() {
  console.log(new Date().toISOString(), '[Test]', 'Running the test');

  const API_URL       = 'https://api.openweathermap.org/data/2.5/weather';
  const API_KEY       = 'c75f89dee2df592ecb5f3386294f4add';
  const LOCATION_CODE = '4608408';  // Brentwood
  const FULL_API_URL  = `${API_URL}?id=${LOCATION_CODE}&appid=${API_KEY}`;

  try {
    const response = await axios.get(FULL_API_URL);
    // 传递API返回的实际天气数据
    this.setResults(response.data);
  } catch (error) {
    console.error(error);
    // 区分不同错误类型生成提示
    let errorMsg = '请求失败,请稍后重试';
    if (error.response) {
      // API返回错误状态码
      errorMsg = `请求错误:${error.response.status} - ${error.response.data.message || '未知错误'}`;
    } else if (error.request) {
      // 无响应,网络问题
      errorMsg = '网络连接失败,请检查网络';
    }
    this.setError(errorMsg);
  }
}

二、修复DOM元素获取的问题

document.getElementsByClassName()返回的是类数组的HTMLCollection,直接设置innerHTML会报错,建议用document.querySelector()获取单个目标元素(适用于页面只有一个.test-results容器的场景):

constructor() {
  // 获取第一个匹配的元素,更可靠
  this.testResults = document.querySelector('.test-results');
}

三、createElement vs innerHTML的选择与实现

场景区分

  • 如果是渲染简单静态内容,innerHTML写法更简洁,对于可信API的数据(如OpenWeatherMap),不存在XSS风险,可放心使用。
  • 如果需要动态生成复杂DOM、绑定事件或操作元素属性,createElement更灵活安全。

方式1:用innerHTML渲染结构化天气数据

修改setResults(),将JSON数据转为可读性强的HTML:

setResults(results) {
  if (!results) {
    this.testResults.innerHTML = '<p>暂无天气数据</p>';
    return;
  }

  // 开尔文转摄氏温度,保留1位小数
  const tempC = (results.main.temp - 273.15).toFixed(1);
  const feelsLikeC = (results.main.feels_like - 273.15).toFixed(1);
  // 天气描述首字母大写
  const weatherDesc = results.weather[0].description.replace(/^\w/, c => c.toUpperCase());

  this.testResults.innerHTML = `
    <div class="weather-card">
      <h2>${results.name}, ${results.sys.country}</h2>
      <div class="weather-main">
        <img src="https://openweathermap.org/img/wn/${results.weather[0].icon}@2x.png" alt="${weatherDesc}">
        <p>${weatherDesc}</p>
      </div>
      <div class="temp-info">
        <p>当前温度:${tempC}°C</p>
        <p>体感温度:${feelsLikeC}°C</p>
        <p>湿度:${results.main.humidity}%</p>
        <p>风速:${results.wind.speed} m/s</p>
      </div>
    </div>
  `;
}

方式2:用createElement构建DOM元素

如果偏好原生DOM操作,setResults()可这么写:

setResults(results) {
  if (!results) {
    this.testResults.innerHTML = '<p>暂无天气数据</p>';
    return;
  }

  // 清空容器原有内容
  this.testResults.innerHTML = '';

  // 创建卡片容器
  const card = document.createElement('div');
  card.classList.add('weather-card');

  // 城市名称
  const title = document.createElement('h2');
  title.textContent = `${results.name}, ${results.sys.country}`;
  card.appendChild(title);

  // 天气图标与描述
  const weatherMain = document.createElement('div');
  weatherMain.classList.add('weather-main');
  
  const weatherIcon = document.createElement('img');
  weatherIcon.src = `https://openweathermap.org/img/wn/${results.weather[0].icon}@2x.png`;
  weatherIcon.alt = results.weather[0].description;
  weatherMain.appendChild(weatherIcon);

  const weatherDesc = document.createElement('p');
  weatherDesc.textContent = results.weather[0].description.replace(/^\w/, c => c.toUpperCase());
  weatherMain.appendChild(weatherDesc);
  card.appendChild(weatherMain);

  // 温度信息组
  const tempInfo = document.createElement('div');
  tempInfo.classList.add('temp-info');

  const tempC = (results.main.temp - 273.15).toFixed(1);
  const feelsLikeC = (results.main.feels_like - 273.15).toFixed(1);

  const tempText = document.createElement('p');
  tempText.textContent = `当前温度:${tempC}°C`;
  tempInfo.appendChild(tempText);

  const feelsLikeText = document.createElement('p');
  feelsLikeText.textContent = `体感温度:${feelsLikeC}°C`;
  tempInfo.appendChild(feelsLikeText);

  const humidityText = document.createElement('p');
  humidityText.textContent = `湿度:${results.main.humidity}%`;
  tempInfo.appendChild(humidityText);

  const windText = document.createElement('p');
  windText.textContent = `风速:${results.wind.speed} m/s`;
  tempInfo.appendChild(windText);

  card.appendChild(tempInfo);
  this.testResults.appendChild(card);
}

四、完善错误提示的格式化

修改setError(),给错误信息添加样式,提升辨识度:

setError(message) {
  this.testResults.innerHTML = `
    <div class="error-message">
      <p>⚠️ ${message || '未知错误'}</p>
    </div>
  `;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 07:15:56