首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用开放天气api AJAX和JS构建5天预报

使用开放天气api AJAX和JS构建5天预报
EN

Stack Overflow用户
提问于 2018-04-04 06:47:11
回答 2查看 10.5K关注 0票数 1

我正在尝试建立一个使用开放天气API的5天预报。我基于网站使用的参数不起作用,它返回未定义的。另外,有没有办法可以从第一天,第二天等等得到主要的温度。请帮助

下面是我的代码:

代码语言:javascript
复制
$.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);
  }
});
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-04-04 10:31:21

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

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

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

代码语言:javascript
复制
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);
  }
});
票数 1
EN

Stack Overflow用户

发布于 2018-04-04 06:57:37

在url中尝试此操作,然后删除data属性

代码语言:javascript
复制
'http://api.openweathermap.org/data/2.5/forecast?appid='+key+'&q='+city+'&count=10'

我不能在没有API键的情况下进行测试,但是文档几乎告诉你该怎么做,http://openweathermap.org/forecast5

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49640174

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档