无法在javascript ..中解析json文件,但出现“ responseObject.weather [i] .weatherresponseObject.weather [i] .description”

尝试使用javascript将数据从json格式的php文件解析为html文件 我正在获取responseObject.weather [i] .weatherresponseObject.weather [i] .description,但我有一个预感,即如何格式化php文件,也许我使用的对象不正确 我正在尝试将温度和说明拉到我的html页面上。 有人可以告诉我哪里出了问题吗?

<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="style.css" rel="stylesheet" type="text/css">
  <script src="run.js"></script>
  <title>Ajax Demo</title>
</head>

<body>
  <h1 class="title">Todays Weather Forecast</h1>
  <p class="sub">Click the button the check the local weather.</p>

  <button class="demo-centered" type="button" onclick="loadPhp()">Check Weather</button><br><br>
  <div id="content"></p>
</body>

</html>

function loadPhp() {
var xhr = new XMLHttpRequest();
xhr.onload = function() {
  if (xhr.status === 200) {
    responseObject = JSON.parse(xhr.responseText);
    var newContent = '';
    for (var i = 0; i < responseObject.weather.length; i++){
      newContent += 'responseObject.weather[i].weather';
      newContent += 'responseObject.weather[i].description';


    }
    document.getElementById('content').innerHTML = newContent;
  }
};

xhr.open('GET', 'demo.php', true);
xhr.send(null);

}

{"coord":{"lon":-116.8,"lat":33.03},"weather":[{"id":802,"main":"Clouds","description":"scattered clouds","icon":"03d"}],"base":"stations","main":{"temp":293.73,"feels_like":289.89,"temp_min":289.26,"temp_max":295.93,"pressure":1016,"humidity":52},"visibility":16093,"wind":{"speed":5.7,"deg":260},"clouds":{"all":40},"dt":1589408840,"sys":{"type":1,"id":5686,"country":"US","sunrise":1589374130,"sunset":1589423903},"timezone":-25200,"id":5391832,"name":"San Diego County","cod":200}
评论
caut
caut

您不需要此代码中的引号:

newContent += 'responseObject.weather[i].weather';
newContent += 'responseObject.weather[i].description';

用引号引起来的是这些文字字符串。代替:

newContent += responseObject.weather[i].weather;
newContent += responseObject.weather[i].description;

...尽管您可能希望在这些标签周围添加一些标记,因为它们只会粘在一起。

其他三件事值得注意:

  1. You never do anything with newContent. You need to do something to put it on the page (append elements with it, append it to existing elements, etc.).

  2. Your code is falling prey to what I call The Horror of Implicit Globals — you need to declare responseObject.

  3. It's fine to use XMLHttpRequest, but you might also look at the newer fetch instead. If you do, though, beware the fetch footgun.

点赞
评论