【发布时间】:2020-05-04 01:08:07
【问题描述】:
我的计算机科学课上的一个项目令人困惑,我不完全确定这些对象是怎么回事。
我必须从这个天气 API 中获取数据,一切顺利,但是由于某种原因,我无法访问返回对象的一部分。
这是我用来获取信息的函数,输入是用户输入的城市名称。我删除了一些位,但只有像 currentTemp 这样的不同变量也能正确响应
function getCurrentWeather(input) {
var APIKey = APIKEY;
var queryURL = "https://api.openweathermap.org/data/2.5/weather?q=" + input + "&appid=" + APIKey;
$.ajax({
url: queryURL,
method: "GET"
}).then(function (response) {
console.log(response);
currentTemp = response.main.temp //THIS ONE WORKS
currentWeather = response.weather.description; //THIS ONE DOESN'T
alert(currentWeather);
});
}
});
这是控制台:
Object {
base: "stations",
clouds: Object {
all: 20
},
cod: 200,
coord: Object {
lat: 42.36,
ion: -71.06
},
dt: 1588552126,
id: 4930956,
main: Object {
feels_like: 288.63,
humidity: 25,
pressure: 1002,
temp: 293.22,
temp_max: 296.15,
temp_min 290.37
},
name: "Boston",
sys: Object {
country: "US",
id: 3486,
sunrise: 1588498564,
sunset: 1588549556,
type: 1
},
timezone: -14400,
visibility: 16093,
weather: [Object {
description: "few clouds",
icon: "02n",
id: 801,
main: "Clouds"
}],
wind: Object {
deg: 280,
speed: 3.6
}
}
天气对象出于某种原因放在括号中,并且它的格式非常奇怪。我正在使用 Codepen,如果这有什么改变的话。
【问题讨论】:
-
天气中的对象是一个具有单个对象的数组(基于
[]的用法)。试试看:response.weather[0].description; -
错字错误
temp_min 290.37=> 缺少:,因此无法读取response.weather -
json 解释器无法读取遵循此语法错误的任何内容
-
不,没有错误。我可能打错了,因为无论出于何种原因,我的计算机都不允许我复制和粘贴控制台。
标签: javascript jquery object