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

使用OpenWeather API、AJAX和JS开发5天天气预报遇问题求助

解决OpenWeather 5天Forecast API的问题

一、为什么返回值是undefined?

你遇到的undefined问题,大概率是遍历对象错误导致的。OpenWeather的forecast接口返回的JSON结构里,实际的天气条目数组是存在data.list中的,而你现在直接遍历顶层的data对象——这相当于在遍历data的属性(比如cod、message、list这些),而非天气数据条目,自然拿不到预期的内容,就会出现undefined。

另外也可以先排查基础问题:

  • 确认city变量是有效的城市名称/ID,key是正确的API密钥(无拼写错误,且已激活Forecast API权限)
  • 可以直接在浏览器地址栏访问API链接,验证返回的JSON结构是否正常,比如:http://api.openweathermap.org/data/2.5/forecast?q=London&appid=你的密钥&units=metric&cnt=10

二、如何获取每天的主温度(main.temp)?

5天Forecast接口每3小时返回一条数据,所以需要先把同一天的数据分组,再提取温度。这里给你两种常用处理方式:

方式1:按日期分组,取当天第一条数据的温度

通过每条数据的dt_txt字段(格式为YYYY-MM-DD HH:MM:SS)提取日期,将同一天的数据归为一组,再取每组第一个数据的温度作为当天主温度:

$.ajax({
  url: 'http://api.openweathermap.org/data/2.5/forecast',
  dataType: 'json',
  type: 'GET',
  data: { 
    q: city, 
    appid: key, 
    units: 'metric', 
    cnt: '10' 
  },
  success: function(data) {
    var wf = '';
    // 用对象存储每天的数据,key为日期字符串(如"2024-05-20")
    var dailyWeather = {};

    // 遍历正确的天气条目数组:data.list
    $.each(data.list, function(index, val) {
      // 提取日期部分,去掉时间
      var date = val.dt_txt.split(' ')[0];
      // 仅存储当天第一条数据
      if (!dailyWeather[date]) {
        dailyWeather[date] = val;
      }
    });

    // 遍历分组后的每日数据,拼接温度信息
    $.each(dailyWeather, function(date, weatherData) {
      var dayTemp = weatherData.main.temp;
      wf += `<p><strong>${date}</strong> 主温度:${dayTemp}°C</p>`;
    });

    // 将结果插入页面元素(示例为#weatherResult)
    $('#weatherResult').html(wf);
  },
  // 新增错误处理,方便排查问题
  error: function(xhr, status, error) {
    console.log('请求错误:', status, error);
    console.log('返回信息:', xhr.responseText);
  }
});

方式2:计算当天所有数据的平均温度

如果需要更精准的温度,可计算同一天所有3小时数据的温度平均值:

success: function(data) {
  var wf = '';
  var dailyTempSum = {};
  var dailyCount = {};

  $.each(data.list, function(index, val) {
    var date = val.dt_txt.split(' ')[0];
    var temp = val.main.temp;

    if (!dailyTempSum[date]) {
      dailyTempSum[date] = 0;
      dailyCount[date] = 0;
    }
    dailyTempSum[date] += temp;
    dailyCount[date] += 1;
  });

  // 遍历计算平均温度
  $.each(dailyTempSum, function(date, sum) {
    var avgTemp = (sum / dailyCount[date]).toFixed(1); // 保留1位小数
    wf += `<p><strong>${date}</strong> 平均温度:${avgTemp}°C</p>`;
  });

  $('#weatherResult').html(wf);
}

三、额外注意事项

  • 确保API密钥已启用5 day forecast权限,免费账户默认开启,但新创建的密钥可能需要等待几分钟生效
  • 接口返回的dt_txt是UTC时间,若需转换为本地时间,可使用val.dt时间戳进行处理
  • 建议使用HTTPS链接:https://api.openweathermap.org/data/2.5/forecast,避免混合内容问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:25:48