尝试将结果从json文件格式化为html

我正在研究一个简单的ajax,javascript和php(json数据提要),只是为了学习。我有点卡住了,我试图用大写json文件中的一个结果的第一个字母....主obj下的.temp需要读取html页面上的Temp:。我尝试使用该函数,但没有出错,但不能同时工作。其次,我想通过CSS或js将DOM查询的结果移动到页面的中心...我在CSS方式上做不到。也许我不了解样式,因为它与onload有关?如果有人可以指出正确的实施方法,我将不胜感激。这是我的代码:html文件,css文件,php文件和javascript。 预先感谢大家。

<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"></div>
<div id="content2"></div>
</body>

</html>

----------------------CSS---------------------------------------
@import url('https://fonts.googleapis.com/css2? 
family=Oxygen&family=Roboto+Mono&family=Source+Code+Pro&display=swap');
/* font-family: 'Source Code Pro', monospace; */
.title {
text-align: center;
font-family: 'Oxygen', sans-serif;
}

#demo {
text-align: center;
font-family: 'Roboto Mono', monospace;
}

.demo-centered {
margin: 0;
position: absolute;
left: 45%;
}

.sub {
font-family: 'Source Code Pro', monospace;
text-align: center;
}

body {
background-image: url(./dave-herring-G5C-CsrmXak-unsplash.jpg);
background-position: center;
background-repeat: no-repeat;
background-size: cover;
}
---------------------------------PHP File-----------------------------
{
"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
}

-----------------------Javascript File ---------------------------

function loadPhp() {
var xhr = new XMLHttpRequest();
xhr.onload = function () {
if (xhr.status === 200) {
  var responseObject = JSON.parse(xhr.responseText);
  var newContent = '';
  var newContent2 = '';


  for (var i = 0; i < responseObject.weather.length; i++) {
    newContent += responseObject.weather[i].description;
  }

  for (var x in responseObject.main){

    if (x === "temp"){
      function capFirst(word){
        return word.charAt(0).toUpperCase() + word.slice(1);
      }
      capFirst(x);
      var z = responseObject.main[x];
      z = Math.round((z - 273.15) * 1.8) + 32;
      document.getElementById('content2').innerHTML =  (x + ':' +z);
    }
  }




  document.getElementById('content').innerHTML = "Description: " + newContent;

 }
};

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

}
评论