如何在api.openweathermap中使用Json Jquery获取天气信息
问题描述:
我有这个api
http://api.openweathermap.org/data/2.5/forecast/daily?q=Montpellier&mode=json&units=metric&cnt=10
然后我将使用Jquery获取信息(城市名称,天气...).
and I will get the information (name of city, weather...) using Jquery .
我该怎么做?
答
使用ajax调用来获取JSON
Use an ajax call to get the JSON like this
$(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:
If you do not want to use 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密钥.
Use your own API key if the one in the URL does not work.