需要列出开放天气图中的数据

问题描述 投票:-1回答:1

我想列出当前天气数据(开放天气图)的数据响应。我使用ajax xhttp请求。我为循环和一个名为output的变量来放置来自for循环的数据。我没有在输出变量中获得任何数据。

我已经尝试了console.log来解析数据。我得到了一些结果。所以api工作,它只是for循环不起作用。

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
    let output = "";
    var data = JSON.parse(this.response);
    console.log(data);

   for(var i = 0; i < data.length; i++){
    output += '<li>' + data[i] + '</li>';
   }
   console.log(output);
   document.getElementById('list').innerHTML = output;
}
};
xhttp.open("GET", "http://api.openweathermap.org/data/2.5/weather? 
q=London&appid=befb83bbddacf33f9ecfc1a5125d7201", true);
xhttp.send();

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Weather api</title>
</head>
<body>
<ul id="list">

</ul>
<script src="app.js"></script>
</body>
</html>
javascript ajax
1个回答
0
投票

API以格式返回对象

{"coord":{"lon":-0.13,"lat":51.51},"weather":anArray}

由于对象没有length属性,因此循环永远不会执行。

据推测,你的意思是反复遍历.weather属性。试试这个:

if (this.readyState == 4 && this.status == 200) {
    let output = "";
    var data = JSON.parse(this.response).weather;
    console.log(data);

   for(var i = 0; i < data.length; i++){
    output += '<li>' + data[i] + '</li>';
   }
   console.log(output);
   document.getElementById('list').innerHTML = output;
}

编辑

连接对象和字符串会隐式调用返回toString的对象的[Object object]方法。您应该将字符串与.description属性连接起来。

试试这个:

if (this.readyState == 4 && this.status == 200) {
    let output = "";
    var data = JSON.parse(this.response).weather;
    console.log(data);

   for(var i = 0; i < data.length; i++){
    output += '<li>' + data[i].description + '</li>';
   }
   console.log(output);
   document.getElementById('list').innerHTML = output;
}
© www.soinside.com 2019 - 2024. All rights reserved.