我正在尝试构建一个简单的代码,在其中获取一些JSON数据(天气信息)并将温度记录到控制台。HEre是我的示例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Simple Weather Application</title>
</head>
<body>
<script>
var cityName = prompt("Please enter city name", "London");
var request = new XMLHttpRequest()
request.open('GET', 'https://api.openweathermap.org/data/2.5/weather?q=' + cityName + '&appid=65a3719d36e2d698392212cd888b5ccf', true)
request.onload = function() {
// Begin accessing JSON data here
var data = JSON.parse(this.response)
if (request.status >= 200 && request.status < 400) {
data => {
console.log(main.temp)
}
} else {
console.log('error')
}
}
request.send()
</script>
</body>
</html>我得到了输入城市名称的提示,值被正确地保存到变量中。但是,我的控制台没有记录温度。
以下是JSON响应的示例:
{
"coord":{
"lon":-0.13,
"lat":51.51
},
"weather":[
{
"id":300,
"main":"Drizzle",
"description":"light intensity drizzle",
"icon":"09d"
}
],
"base":"stations",
"main":{
"temp":280.32,
"pressure":1012,
"humidity":81,
"temp_min":279.15,
"temp_max":281.15
},
"visibility":10000,
"wind":{
"speed":4.1,
"deg":80
},
"clouds":{
"all":90
},
"dt":1485789600,
"sys":{
"type":1,
"id":5091,
"message":0.0103,
"country":"GB",
"sunrise":1485762037,
"sunset":1485794875
},
"id":2643743,
"name":"London",
"cod":200
}你知道我可能做错了什么吗?
提前感谢你的帮助。
我已经搜索了几个关于如何做到这一点的代码示例。
我想让控制台记录温度。还有,有人知道如何将温度从开尔文换算成摄氏度吗?
发布于 2019-05-15 19:03:48
<script>
var cityName = prompt("Please enter city name", "London");
var request = new XMLHttpRequest()
request.open('GET', 'https://api.openweathermap.org/data/2.5/weather?q=' + cityName + '&appid=65a3719d36e2d698392212cd888b5ccf', true)
request.onload = function() {
// Begin accessing JSON data here
if (request.status == 200) {
var data = JSON.parse(this.responseText);
let temperature = data.main.temp - 273.15;
console.log(temperature);
} else {
console.log('error')
}
}
request.send()
</script>https://stackoverflow.com/questions/56147252
复制相似问题