嗨,我是JSON和JavaScript的新手,想浏览OpenWeatherMap API的JSON输出以获取某些数据。
有人知道我该怎么做吗?
提前谢谢
答案 0 :(得分:0)
来自d.weather的示例API天气
api.openweathermap.org/data/2.5/forecase?lat=50.8609&lon=-0.08014&&units=metric
用于提取openweather JSON数据的HTML页面
<html>
<head>
<title>Weather</title>
<meta charset="utf-8">
<script src="http://code.jquery.com/jquery-1.7.min.js" ></script>
<script src="http://code.jquery.com/ui/1.7.0/jquery-ui.js" ></script>
<script>
function getWeather(callback) {
var weather = 'http://api.openweathermap.org/data/2.5/forecast?lat=51.5072&lon=0.1275&units=metric';
$.ajax({
dataType: "jsonp",
url: weather,
success: callback
});
}
// get data:
getWeather(function (data) {
console.log('weather data received');
console.log(data.list[0].weather[0].description);
console.log(data.list[0].weather[0].main);
});
getWeather(function (data) {
document.write('weather data received');
document.write('<br>');
document.write(data.list[0].weather[0].description);
document.write('<br>');
document.write(data.list[0].weather[0].main);
document.write('<br>');
document.write(data.list[0].main.temp);
document.write('<br>');
document.write(data.list[0].main[0].dt_txt);
document.write('<br>');
});
</script>
</body>
</html>
用于提取JSON数据的HTML页面
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.0.min.js"></script>
<!-- Javascript -->
<script type="text/javascript">
function loadUrl(newLocation){
window.location = newLocation;
return false;
}
</script>
<script type="text/javascript">
$(document).ready(function (){
$("#btn382").click(function(){
/* set no cache */
$.ajaxSetup({ cache: false });
$.getJSON("weather.json", function(data){
var html = [];
/* loop through array */
$.each(data, function(index, d){
html.push("Team : ", d.Teams, ", ",
"Long : ", d.Long, ", ",
"Lat : ", d.Lat, ", ",
"Weather : ", d.Weather, "<br>");
});
$("#div381").html(html.join('')).css("background-color", "orange");
}).error(function(jqXHR, textStatus, errorThrown){ /* assign handler */
/* alert(jqXHR.responseText) */
alert("error occurred!");
});
});
});
</script>
<!-- HTML -->
<a name="#ajax-getjson-example"></a>
<div id="example-section38">
<div>Football weather</div>
<div id="div381"></div>
<button id="btn382" type="button">Team location</button>
</div>
weather.json
{
"Teams":"Wycombe Wanderers",
"Long":-0.800299,
"Lat":51.6306,
"Weather":" api.openweathermap.org/data/2.5/weather?lat=51.6306&lon=-0.800299&mode=html"
},
{
"Teams":"Livingston",
"Long":-3.52207,
"Lat":55.8864,
"Weather":" api.openweathermap.org/data/2.5/weather?lat=55.8864&lon=-3.52207&mode=html"
},
{
"Teams":"Brighton and Hove Albion",
"Long":-0.08014,
"Lat":50.8609,
"Weather":" api.openweathermap.org/data/2.5/weather?lat=50.8609&lon=-0.08014&mode=html"
},