【问题标题】:OpenWeatherMap.ORG API - $.getJSON doesn't work and I'm not recieving any dataOpenWeatherMap.ORG API - $.getJSON 不起作用,我没有收到任何数据
【发布时间】:2017-01-28 06:23:53
【问题描述】:

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

如果我使用浏览器访问网址:

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

然后,我得到了正确的 Json: {"coord":{"lon":145.77,"lat":-16.92},"weather":[{"id":803,"main":"Clouds","description":"破云"," icon":"04n"}],"base":"stations","main":{"temp":289.26,"pressure":1013,"humanity":93,"temp_min":289.26,"temp_max": 289.26},"wind":{"speed":1.61,"deg":116.5},"rain":{"3h":0.03},"clouds":{"all":76},"dt":1474367584 ,"sys":{"type":3,"id":10843,"message":0.1585,"country":"AU","sunrise":1474315673,"sunset":1474359164},"id":2172797 ,"名称":"凯恩斯","鳕鱼":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)});


});

代码笔:https://codepen.io/elivanrock/pen/zKoYEj?editors=1011

提前致谢!

【问题讨论】:

  • 检查浏览器的控制台。 HTTP-HTTPS 问题。如果你通过 http 加载 codepen,你的代码就可以工作。
  • 非常感谢尤里!

标签: javascript jquery openweathermap


【解决方案1】:

您可以使用来自 openweathermap.com 的 JSONp 获取数据,只需以这种方式添加您的回调函数:

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>

【讨论】:

    猜你喜欢
    • 2020-07-22
    • 2020-08-08
    • 1970-01-01
    • 2012-06-14
    • 2013-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多