2014-12-06 102 views

回答

4

使用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

+0

是的,但我怎么能显示例如城市的名称和天气使用这个? – HamidS 2014-12-06 21:44:09

+0

我已更新我的答案,并添加小提琴 – 2014-12-06 21:54:17

+0

好吧谢谢你+即时通讯添加你在Facebook上检查你的收件箱 – HamidS 2014-12-06 21:56:32

0

就发出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。