我正在尝试构建一个简单的代码,其中我获取一些JSON数据(天气信息(并将温度记录到控制台。这是我的示例代码:
<!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
}
知道我可能做错了什么?
事先感谢您的帮助。
我已经搜索了几个有关方法的代码示例。
我想让控制台记录温度。另外,有人知道如何将温度从开尔文转化为摄氏吗?
<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) {
// kelvin to celsius formula is celsius = Kelvin - 273.15
console.log(`${data.main.temp - 273.15}C`)
} else {
console.log('error')
}
}
request.send()
</script>
基本对象上没有属性temp
- 它在嵌套的data
对象中:
console.log(data.main.temp);
<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) {
((main)=>{
console.log(main.temp)
})(data.main)
} else {
console.log('error')
}
}
request.send()
</script>
<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>