【发布时间】:2015-02-04 20:19:40
【问题描述】:
我有这个 api
http://api.openweathermap.org/data/2.5/forecast/daily?q=Montpellier&mode=json&units=metric&cnt=10
我将使用 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();
【讨论】:
只需发出 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。
【讨论】: