>我有这个接口
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。