新手在这里,我正在尝试从FreeWeatherCamp的一个项目的OpenWeatherMap API访问温度。但是我的问题是,每当我尝试使用嵌套的JSON对象访问温度值时,控制台都会提示“ temp”的父级未定义。为什么未定义?
这是给我问题的代码:
$.getJSON(url, function(data) {
console.log("successful request");
console.log(data.main.temp);
console.log("successful temperature access");
});
当我运行此命令时,控制台记录“成功请求”,然后显示错误信息:
Uncaught TypeError-无法读取未定义的属性'temp'(...)。
我尝试过的事情:我查看了示例代码并参考了API文档,发现
data.main.temp
是访问温度的有效方法。我验证了data
对象已解析,并确保它不包含在数组中。另外,我已经验证了网址。这是URL导致的起始代码段:link.
正在使用Chrome。 Link到Codepen项目。
最佳答案
天气数据以字符串形式返回。您需要像这样将其解析为JSON:
$.getJSON(url, function(data) {
var weatherData = JSON.parse(data.content);
console.log("successful request");
console.log(weatherData.main.temp);
console.log("successful temperature access");
});
关于javascript - OpenWeatherMap API:未捕获的TypeError-无法读取未定义的属性“temp”(…),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41402181/