如何在api.openweathermap中使用Json Jquery来获取天气信息
我有这个api
http://api.openweathermap.org/data/2.5/forecast/daily?q=Montpellier&mode=json&units=metric&cnt=10
我将使用Jquery获取信息(城市名称,天气……)。
我怎么能这样做?
使用ajax调用来获取这样的JSON
$(document).ready(function(){ $.getJSON("http://api.openweathermap.org/data/2.5/forecast/daily?q=Montpellier&mode=json&units=metric&cnt=10",function(result){ alert("City: "+result.city.name); alert("Weather: "+ result.list[0].weather[0].description); }); });
这是小提琴: http : //jsfiddle.net/cz7y852q/
如果你不想使用jQuery:
var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == XMLHttpRequest.DONE ) { if (xmlhttp.status == 200) { var data = JSON.parse(xmlhttp.responseText); //access json properties here alert("Weather: "+ data.weather[0].description); } else if (xmlhttp.status == 400) { alert('There was an error 400'); } else { alert('something else other than 200 was returned'); } } }; xmlhttp.open("GET", "http://api.openweathermap.org/data/2.5/weather?id=524901&APPID=7dba932c8f7027077d07d50dc20b4bf1", true); xmlhttp.send();
如果URL中的API密钥不起作用,请使用您自己的API密钥 。
只需发出ajax GET请求:
var url = "http://api.openweathermap.org/data/2.5/forecast/daily?q=Montpellier&mode=json&units=metric&cnt=10" $.getJSON(url).then(function(data) { console.log(data); });
api.openweathermap.org实现了CORS,这意味着您不会遇到跨域问题,只需使用AJAX请求API即可。