我有這個API我如何使用JSON的Jquery在api.openweathermap獲取天氣信息
http://api.openweathermap.org/data/2.5/forecast/daily?q=Montpellier&mode=json&units=metric&cnt=10
,我會得到使用jQuery的信息(城市名稱,天氣...)。
我該怎麼做?
我有這個API我如何使用JSON的Jquery在api.openweathermap獲取天氣信息
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 key。
就發出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,這意味着你不會有跨域問題,可以簡單地請求API使用AJAX。
是的,但我怎麼能顯示例如城市的名稱和天氣使用這個? – HamidS 2014-12-06 21:44:09
我已更新我的答案,並添加小提琴 – 2014-12-06 21:54:17
好吧謝謝你+即時通訊添加你在Facebook上檢查你的收件箱 – HamidS 2014-12-06 21:56:32