2016-10-10 153 views
0

我正在學習API,並且是該流程的初學者,任何幫助都很有價值。以HTML格式顯示API響應

我已經設法得到數據即時尋找作爲XML響應,並有console.logged它在鉻。我不確定如何實際訪問此#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

我搜索了整個週末,我找不到我能夠理解的解決方案。

在此先感謝

回答

-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); 
 
\t $place = "capetown,za"; 
 
\t $json_string = file_get_contents("http://api.openweathermap.org/data/2.5/weather?q=$place&units=metric&APPID=API-KEY-GOES-HERE"); 
 
\t $parsed_json = json_decode($json_string); 
 
\t $country = $parsed_json->sys->country; 
 
\t $wind = $parsed_json->wind->speed; 
 
\t $city = $parsed_json->name; 
 
\t $temp = $parsed_json->main->temp; 
 
\t $clouds = $parsed_json->weather[0]->description; 
 
\t if($clouds == "clear sky"){ 
 
\t \t echo ("<img src='http://placehold.it/200x200'>"); 
 
\t } 
 
?> 
 

 
<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>

+0

爲什麼下跌投票? – anthonytherockjohnson