【问题标题】:Issue with getting data from api从 api 获取数据的问题
【发布时间】:2017-04-22 12:25:48
【问题描述】:

我正在尝试调用两个 api。第一个是成功返回数据。第二个不是。请有人帮忙

$(function() {
      $.getJSON('https://freegeoip.net/json/').done(function(location) {
        $("div").html(JSON.stringify(location));

        $.getJSON('http://api.openweathermap.org/data/2.5/weather?lat=' + location.latitude + '&lon=' + location.longitude + '&units=imperial&appid=b3ce5b75f220eaf1db1df46a93a6595e',
          function(data) {
            console.log(data);
          });
      });
    });

【问题讨论】:

  • “第二个不是”是什么意思?您遇到了什么错误?
  • 您的代码在我的浏览器上运行正常。
  • 您是否要在 https 域上加载它?您在控制台中遇到什么错误?因为你的代码看起来不错。
  • 我在控制台中没有收到任何错误。我在 codepen.io 做。 codepen.io 是 https。
  • 从 url 中删除 https:// 并再次访问它应该可以工作。但这并不能真正解决您的问题。

标签: jquery json api


【解决方案1】:

http 的问题是 https://codepen.io 是通过 https 协议加载的,但请求的 XMLHttpRequest 端点不安全。

http://api.openweathermap.org/data/2.5/weather?lat=17.3753&lon=78.4744&units=imperial&appid=b3ce5b75f220eaf1db1df46a93a6595e

因此,此请求已被阻止;内容必须通过 HTTPS 提供或直接在应用程序中注入您的代码,而不是通过在线工具运行。

演示

$(function() {
      $.getJSON('https://freegeoip.net/json/').done(function(location) {
        $("div").html(JSON.stringify(location));

        $.getJSON('http://api.openweathermap.org/data/2.5/weather?lat=' + location.latitude + '&lon=' + location.longitude + '&units=imperial&appid=b3ce5b75f220eaf1db1df46a93a6595e',
          function(data) {
            console.log(data);
          });
      });
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>

【讨论】:

    猜你喜欢
    • 2019-03-05
    • 2018-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-05
    • 2021-01-18
    • 2015-10-14
    • 2011-11-16
    相关资源
    最近更新 更多