Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ajax/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 需要列出开放天气图中的数据_Javascript_Ajax - Fatal编程技术网

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

Javascript 需要列出开放天气图中的数据,javascript,ajax,Javascript,Ajax,我想列出当前天气数据(开放天气图)的数据响应。我使用ajaxhttp请求。I for循环和一个名为output的变量,用于放置for循环中的数据。我在输出变量中没有得到任何数据 我已经尝试了console.log以获取数据,该数据已被解析。我得到了一些结果。因此api可以工作,只有for循环不起作用 var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4

我想列出当前天气数据(开放天气图)的数据响应。我使用ajaxhttp请求。I for循环和一个名为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();
var xhttp=new-XMLHttpRequest();
xhttp.onreadystatechange=函数(){
if(this.readyState==4&&this.status==200){
让输出=”;
var data=JSON.parse(this.response);
控制台日志(数据);
对于(变量i=0;i';
}
控制台日志(输出);
document.getElementById('list').innerHTML=输出;
}
};
xhttp.open(“GET”http://api.openweathermap.org/data/2.5/weather? 
q=伦敦&appid=BEFB83BBDDACF3F9ECFC1A5125D7201”,正确);
xhttp.send();
Html:


天气空气污染指数

API以以下格式返回对象

{“coord”:{“lon”:-0.13,“lat”:51.51},“weather”:anArray}
由于对象没有长度属性,因此将永远不会执行循环

您可能打算迭代
.weather
属性。 试试这个:

if(this.readyState==4&&this.status==200){
让输出=”;
var data=JSON.parse(this.response).weather;
控制台日志(数据);
对于(变量i=0;i';
}
控制台日志(输出);
document.getElementById('list').innerHTML=输出;
}
编辑

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

试试这个:

if(this.readyState==4&&this.status==200){
让输出=”;
var data=JSON.parse(this.response).weather;
控制台日志(数据);
对于(变量i=0;i';
}
控制台日志(输出);
document.getElementById('list').innerHTML=输出;
}

谢谢:)这是朝着正确方向迈出的一步。我现在在html页面中得到一个列表元素。上面写着物体。所以我需要正确筛选。如何使用.description属性?
<!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>