2016-09-20 32 views
0

我正在尝试使用providen api连接到openweather.org的测试代码。

如果我用我的浏览器访问URL:

http://api.openweathermap.org/data/2.5/weather?id=2172797&APPID=35000cdad97645316c048563e4183021

然后,我得到了正确的JSON: { “坐标”:{ “LON”:145.77, “LAT”: - 16.92 },“weather”:[{“id”:803,“main”:“Clouds”,“description”:“broken clouds”,“icon”:“04n”}],“base”主 “:{” 温度 “:289.26,” 压力 “:1013,” 湿度 “:93,” temp_min “:289.26,” temp_max “:289.26},” 风 “:{” 速度 “:1.61,” DEG“: 116.5}, “雨”:{ “3H”:0.03}, “云”:{ “所有”:76}, “DT”:1474367584, “SYS”:{ “类型”:3, “ID”:10843, “message”:0.1585,“country”:“AU”,“sunrise”:1474315673,“sunset”:1474359164},“id”:2172797,“name”:“凯恩斯”,“cod”:200}

问题是,当我使用jQuery的$ .getJSON时,我看不到任何数据。

这是为什么?如何解决?

JS:

$(document).ready(function(){ 

    var api = 'http://api.openweathermap.org/data/2.5/weather?id=2172797&APPID=35000cdad97645316c048563e4183021'; 

    $.getJSON(api, {format:'json'},function(data){console.log(data.coord.lon)}); 


}); 

CodePen:https://codepen.io/elivanrock/pen/zKoYEj?editors=1011

先谢谢了!

+1

检查**浏览器** 安慰。 HTTP-HTTPs问题。如果你通过http加载codepen,你的代码就可以工作。 – yuriy636

+0

非常感谢Yuri! –

回答

1

你可以使用JSONP从openweathermap.com数据,只需添加您的回调函数是这样的:下面

http://api.openweathermap.org/data/2.5/weather?id=2172797&APPID=35000cdad97645316c048563e4183021&callback=myfunc 

例子:

$.ajax({ 
 
    url: "http://api.openweathermap.org/data/2.5/weather", 
 
    jsonp: "callback", 
 
    dataType: "jsonp", 
 
    data: { 
 
     id: "2172797", 
 
     APPID: "35000cdad97645316c048563e4183021" 
 
    }, 
 
    success: function(response) { 
 
     console.log(response); // server response 
 
     $('.current').html('<img src="http://openweathermap.org/img/w/' + response.weather[0].icon + '.png" /> ' + response.weather[0].main); 
 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="current"></div>