【问题标题】:Displaying API response in HTML在 HTML 中显示 API 响应
【发布时间】:2017-02-18 12:44:37
【问题描述】:

我正在学习 API,并且完全是该过程的初学者,任何帮助都会很有价值。

我已经设法将我正在寻找的数据作为 XML 响应获取,并将 console.logged 到 chrome 中。我不确定如何实际访问我在控制台中看到的这个#document,请参阅下面的代码和控制台打印输出

<!doctype html>
<html>
<head>

<script>
window.onload = function() {
var xhr = new XMLHttpRequest();
xhr.open("GET","http://api.openweathermap.org/data/2.5/weather?lat=35&lon=139&mode=xml&APPID=92cc96ecfe265f251d814b66592a7848",false);
xhr.send();
console.log(xhr.status);
console.log(xhr.statusText);
console.log(xhr.responseXML);
var response = xhr.responseXML;
var xmlString = (new XMLSerializer()).serializeToString(response);
if(xhr.status == 200){
document.getElementById("document").innerHTML = xmlString;
}
}
</script>
<meta charset="UTF-8">
<title>Weather API Test</title>
</head>

<body id="body">
<div id="document"></div>
</body>
</html>

控制台显示:

200
OK
#document
  all of the XML is contained in here that I need to access and display

我已经搜索了整个周末,但找不到我能够理解的解决方案。

提前致谢

【问题讨论】:

    标签: xml parsing weather-api openweathermap


    【解决方案1】:

    我设法通过使用 PHP 和 JSON 作为替代方案来解决这个问题 - 在下面发布以帮助处于同样困境的其他人

    <!doctype html>
    <html>
    <head>
    
    
    
    <meta charset="UTF-8">
    <title>API TEST JSON</title>
    </head>
    
    <body>
    <?php
    error_reporting(E_ALL);
    ini_set('display_errors', 1);
    	$place = "capetown,za";
    	$json_string = file_get_contents("http://api.openweathermap.org/data/2.5/weather?q=$place&units=metric&APPID=API-KEY-GOES-HERE");
    	$parsed_json = json_decode($json_string);
    	$country = $parsed_json->sys->country;
    	$wind = $parsed_json->wind->speed;
    	$city = $parsed_json->name;
    	$temp = $parsed_json->main->temp;
    	$clouds = $parsed_json->weather[0]->description;
    	if($clouds == "clear sky"){
    		echo ("<img src='http://placehold.it/200x200'>");
    	}
    ?>
    
    <table border="1px solid black">
    <tr>
    <td style="color:red;">Country</td>
    <td style="color:red;"><?php echo $country;?></td>
    </tr>
    <tr>
    <td style="color:red;">City</td>
    <td style="color:red;"><?php echo $city;?></td>
    </tr>
    <tr>
    <td style="color:red;">Temperature</td>
    <td style="color:red;"><?php echo $temp;?></td>
    </tr>
    <tr>
    <td style="color:red;">Wind Speed M/S</td>
    <td style="color:red;"><?php echo $wind;?></td>
    </tr>
    <tr>
    <td style="color:red;">Cloudiness</td>
    <td style="color:red;"><?php echo $clouds;?></td>
    </tr>
    </table>
    </body>
    </html>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-10
      • 1970-01-01
      • 2018-11-29
      • 2019-01-01
      • 1970-01-01
      • 2015-04-16
      • 2020-04-20
      • 1970-01-01
      相关资源
      最近更新 更多