【问题标题】:building a 5 day forecast using open weather api AJAX and JS [closed]使用开放天气 api AJAX 和 JS 构建 5 天预报 [关闭]
【发布时间】:2025-12-30 09:15:13
【问题描述】:

我正在尝试使用开放天气 API 构建 5 天预报。我基于网站使用的参数不起作用,它返回未定义。另外,有什么方法可以让我从第 1 天、第 2 天等获得主要温度。请帮助

这是我的代码:

$.ajax({
  url: 'http://api.openweathermap.org/data/2.5/forecast', //API Call
  dataType: 'json',
  type: 'GET',
  data: {
    q: city,
    appid: key,
    units: 'metric',
    cnt: '10'
  },
  success: function(data) {
    var wf = '';
    $.each(data, function(index, val) {
      wf += '<p><b>' + data.city.name + '</b><img src=http://openweathermap.org/img/w/' + data.list[0].weather.icon + '.png></p>' + data.list[0].main.temp + '&deg;C' + ' | ' + data.list[0].weather.main + ", " + data.list[0].weather.description
    });
    $("#showWeatherForcast").html(wf);
  }
});

【问题讨论】:

标签: javascript ajax api openweathermap


【解决方案1】:

您当前的代码离您不远了。我建议您在 success 函数中使用 console.log(data) 来查看测试时弹出的内容。它将帮助您了解返回的数据结构。

如果您现在查看浏览器控制台,您可能会看到一些警告。我建议您对主要 API 调用和图像 URL 使用 https 而不是 http URL,以避免其中一些,包括混合内容警告。

以下代码改编自您的代码,并在data.listcity 中为每个val 显示温度、描述和一个图标。请注意,这里的$.each 循环遍历数组data.list 中每个val (0-9) 的属性,以访问您需要的数据。您当前的代码每次尝试访问data.list[0][some property] 中的val,返回undefined

var key = "YOUR KEY";
var city = "YOUR CITY"; // My test case was "London"
var url = "https://api.openweathermap.org/data/2.5/forecast";

$.ajax({
  url: url, //API Call
  dataType: "json",
  type: "GET",
  data: {
    q: city,
    appid: key,
    units: "metric",
    cnt: "10"
  },
  success: function(data) {
    console.log('Received data:', data) // For testing
    var wf = "";
    wf += "<h2>" + data.city.name + "</h2>"; // City (displays once)
    $.each(data.list, function(index, val) {
      wf += "<p>" // Opening paragraph tag
      wf += "<b>Day " + index + "</b>: " // Day
      wf += val.main.temp + "&degC" // Temperature
      wf += "<span> | " + val.weather[0].description + "</span>"; // Description
      wf += "<img src='https://openweathermap.org/img/w/" + val.weather[0].icon + ".png'>" // Icon
      wf += "</p>" // Closing paragraph tag
    });
    $("#showWeatherForcast").html(wf);
  }
});

【讨论】:

    【解决方案2】:

    在 url 中试试这个并删除 data 属性

    'http://api.openweathermap.org/data/2.5/forecast?appid='+key+'&q='+city+'&count=10'
    

    没有 api 密钥我无法测试,但文档几乎告诉你该怎么做http://openweathermap.org/forecast5

    【讨论】: