我正在使用OpenWeatherMap API,似乎无法弄清楚为什么我的一个字段显示为未定义。除了当我尝试检索天气状况(位于weather.description上)时,一切都正常,它返回的是undefined。所有其他变量都可以正确填写。任何人都知道是什么会阻止它正常工作? 我的JavaScript:
namespace DocumentStore.IntegrationTests
{
public static class Constants
{
public const string Test1 = "https://documentstore1.dev.namespace.net/v2/service.svc/basicNoAuth";
public const string Test2 = "https://documentstore1.dev.namespace.net/v2/service.svc";
}
public class Tests
{
[Theory]
[InlineData(Constants.Test1)]
[InlineData(Constants.Test2)]
public void ExampleTest(string url)
{
var test = url;
}
}
}
我的HTML
var request = new XMLHttpRequest();
function getWeather() {
var latitude = document.getElementById("lat").value;
var longitude = document.getElementById("long").value;
request.open('GET', 'https://api.openweathermap.org/data/2.5/weather?lat=' + latitude + '&lon=' + longitude + '&units=imperial&appid=547fa6dfa44cff13fa92bba2c465b366', true);
request.send();
request.onreadystatechange = displayData;
}
function displayData() {
if(request.readyState === 4 && request.status === 200) {
var resultData = JSON.parse(request.responseText);
var location = document.getElementById("location")
var temperature = document.getElementById("temperature");
var windspeed = document.getElementById("windspeed");
var condition = document.getElementById("condition");
location.value = resultData.name +", " + resultData.sys.country;
temperature.value = resultData.main.temp + " degrees Fahrenheit";
windspeed.value = resultData.wind.speed + " miles per hour";
condition.value = resultData.weather.description;
document.getElementById("resultset").style.visibility = "visible";
}
}
// Create an event handler for when the btn button is clicked
window.onload = function() {
var btn = document.getElementById("btn");
btn.addEventListener("click", getWeather, false);
}
答案 0 :(得分:1)
如果看到API at the OpenWeatherMap site,我们将看到weather
属性是一个数组。要访问天气的描述,请尝试weather[0].description
,或者更好的方法是,循环浏览并提取每种天气情况的描述(如果适合您的用例)。