【发布时间】: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