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

使用fetch调用天气API时,无法修改HTML文本元素的解决方法

问题修复方案

核心问题分析

你的代码存在几个关键问题导致页面无变化:

  • 请求的API是OpenWeatherMap,但携带了RapidAPI的请求头,导致请求被拒绝
  • 赋值给main元素的是温度数据,而非目标天气状况字段
  • 硬编码了城市名,没有使用输入框的用户输入
  • 缺少错误捕获,无法排查请求失败原因

修复步骤

  1. 移除无效请求头:OpenWeatherMap的API不需要RapidAPI的headers,直接删除多余的options参数
  2. 修正数据路径:将json.main.temp改为json.weather[0].main,对应天气状况字段
  3. 动态使用输入城市:把请求URL里的london替换为输入框的CityInput.value
  4. 添加错误处理:用.catch()捕获请求或解析错误,方便调试排查
  5. 同步DOM更新时机:将城市名称更新放到fetch成功回调里,确保和天气数据同步展示

修复后的完整代码

const CityInput = document.getElementById("input");
const btn = document.getElementById("search");
const Cityname = document.getElementById("cityname");

const main = document.getElementById("main");
const Temp = document.getElementById("Temp");

btn.addEventListener("click", Citytemp);

function Citytemp() {
  const city = CityInput.value.trim();
  if (!city) return; // 空输入不发起请求

  fetch(
    `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=a8e71c9932b20c4ceb0aed183e6a83bb&units=imperial`
  )
  .then((response) => {
    if (!response.ok) throw new Error(`请求失败:${response.status}`);
    return response.json();
  })
  .then((json) => {
    main.innerText = json.weather[0].main;
    Cityname.innerHTML = city;
    Temp.innerText = `${json.main.temp}°F`; // 可选:同步展示温度
  })
  .catch((error) => {
    console.error(error);
    main.innerText = "获取天气失败";
  });
}

额外注意事项

  • 确认OpenWeatherMap API密钥有效,避免因密钥过期导致请求失败
  • 检查DOM元素的id是否和代码中的getElementById参数一致,确保元素能被正确获取
  • 可通过浏览器开发者工具的「网络」标签查看请求状态,验证API响应是否正常

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 11:17:02