我正在尝试建立一个使用开放天气API的5天预报。我基于网站使用的参数不起作用,它返回未定义的。另外,有没有办法可以从第一天,第二天等等得到主要的温度。请帮助
下面是我的代码:
$.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 + '°C' + ' | ' + data.list[0].weather.main + ", " + data.list[0].weather.description
});
$("#showWeatherForcast").html(wf);
}
});发布于 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。
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 + "°C" // 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);
}
});发布于 2018-04-04 06:57:37
在url中尝试此操作,然后删除data属性
'http://api.openweathermap.org/data/2.5/forecast?appid='+key+'&q='+city+'&count=10'我不能在没有API键的情况下进行测试,但是文档几乎告诉你该怎么做,http://openweathermap.org/forecast5
https://stackoverflow.com/questions/49640174
复制相似问题