【问题标题】:Very simple API call that doesn't return anything不返回任何内容的非常简单的 API 调用
【发布时间】:2016-09-16 00:33:10
【问题描述】:

我正在尝试从开放天气 API 获取数据,但我得到的只是一个我无法使用的对象(JSON 在里面,但我无法访问它)

我读过很多关于异步 JS 和回调的文章。我真的不确定是否需要对我正在使用的每个 API 进行回调,我已经使用了一个来获取纬度和经度,但是现在,对于开放天气 API,我需要将这些纬度和经度作为 API 的参数传递调用,如果我使用回调,我不知道该怎么做(因为似乎回调函数中的参数不是函数中使用的参数,而是实际返回的参数,我觉得这非常令人困惑)。

谁能告诉我我在这里做错了什么?

$(document).ready(function() {
  $('#getWeather').on('click', function(){
    myLatAndLon(function(result) {
      var lat = result[0];
      var lon = result[1];
      console.log(myWeather(lat, lon));
      // Here, although the params work in browser, the message that gets returned in console is : "NS_ERROR_DOM_BAD_URI: Access to restricted URI denied"
    });
  })
})

function myLatAndLon(callback) {
  $.getJSON('http://ip-api.com/json/').done( function(location) {
    var arr = [];
    arr.push(location.lat);
    arr.push(location.lon);
    callback(arr);
  });
}

function myWeather(lat, lon) {
  return $.getJSON('http://api.openweathermap.org/data/2.5/weather', {
      lat: lat,
      lon: lon,
      APPID: 'a9c241803382387694efa243346ec4d7'
  })
  // The params are good, and when I type them on my browser, everything works fine
}

【问题讨论】:

  • 您是否尝试在网址开头添加http://
  • 嘿,是的,对不起,我正在编辑我的帖子;问题是,我得到了一个对象,但我无法获取 JSON,每次我尝试获取它时,它都会返回 undefined...
  • 你解析过你的 JSON 吗? JSON.parse(returned_string);
  • 我刚试过,我得到“SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data”
  • 我在企业防火墙后面,所以我看不到你的照片。返回的对象里面有什么?它是否包含您的天气数据?

标签: javascript api


【解决方案1】:

将您的代码更改为它并再次测试:

$(document).ready(function() {
  $('#get').on('click', function() {
    myLatAndLon(function(result) {
      var lat = result[0];
      var lon = result[1];
      alert(JSON.stringify(result));
      $req = myWeather(lat, lon);
      $req.done(function(R) {
        alert(JSON.stringify(R))
      });
    });
  })
})

function myLatAndLon(callback) {
  $.getJSON('//ip-api.com/json/').done(function(location) {
    var arr = [];
    arr.push(location.lat);
    arr.push(location.lon);
    callback(arr);
  });
}

function myWeather(lat, lon) {
  return $.getJSON('//api.openweathermap.org/data/2.5/weather', {
    lat: lat,
    lon: lon,
    APPID: 'a9c241803382387694efa243346ec4d7'
  })
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="get">get</button>

您还应该检查您的服务器是否有CORS 限制,请在此处阅读更多信息: http://enable-cors.org/server.html

【讨论】:

  • 您好,非常感谢您的回答,我试过了,可惜并没有改变结果;最后我得到了一个里面有 JSON 的对象,但我仍然无法访问那个 JSON...
  • 等待我在小提琴中测试
  • 非常感谢,我只是添加了一张图片以使其更清晰
  • 老兄我反复检查没有问题我真的确定你有CORS问题请更改服务器中的设置并再次测试如果你真的不知道该怎么做请提及您的服务器信息以帮助您。
  • 也可以看到这篇文章:stackoverflow.com/questions/6653825/…
猜你喜欢
  • 2014-03-31
  • 1970-01-01
  • 1970-01-01
  • 2019-03-05
  • 1970-01-01
  • 1970-01-01
  • 2020-05-18
  • 2017-12-28
  • 1970-01-01
相关资源
最近更新 更多