我有一个$ .getJSON请求,从API中提取数据。我需要从该请求中提取数据以在其外部使用。这是代码:
var weatherData = "http://api.openweathermap.org/data/2.5/weather?q=Location,us&appid=APIkey";
$.getJSON(weatherData,function(data){
var icon = data.weather[0].icon;
});
var skycons = new Skycons();
var conditions = [
"clear-day", "clear-night", "partly-cloudy-day",
"partly-cloudy-night", "cloudy", "rain", "sleet", "snow", "wind",
"fog"], i;
var icons = ["01d", "01n", "02d", "02n", "03d", "09d", "13d", "50d"];
if (icon == "03n" || icon == "04d" || icon == "04n")
icon = "03d";
if (icon == "09n" || icon == "10d" || icon == "10n" || icon == "11d" || icon == "11n")
icon = "09d";
if (icon == "13n")
icon = "13d";
if (icon == "50n")
icon = "50d";
for(i = conditions.length; i--; )
skycons.set(conditions[i], conditions[i]);
skycons.play();
显然,问题是我需要能够访问“ var icon = data.weather [0] .icon;”。在$ .getJSON请求之外。
我了解jQuery是异步的。我已经阅读了这里的所有相关问题,但我无法理解答案。请使其尽可能简单。
答案 0 :(得分:0)
万一有人碰到了我的代码并且也在使用Skycons,这就是我结合Openweathermap的API来根据我所在位置的当前天气情况显示相应的Skycon的方式。
var weatherData = "http://api.openweathermap.org/data/2.5/weather?q=Location,us&appid=APIkey";
$.getJSON(weatherData,function(data){
var icon = data.weather[0].icon;
var skycons = new Skycons();
var conditions = [
"clear-day", "clear-night", "partly-cloudy-day",
"partly-cloudy-night", "cloudy", "rain", "sleet", "snow", "wind",
"fog"], i;
var icons = ["01d", "01n", "02d", "02n", "03d", "09d", "13d", "50d"];
if (icon == "03n" || icon == "04d" || icon == "04n")
icon = "03d";
if (icon == "09n" || icon == "10d" || icon == "10n" || icon == "11d" || icon == "11n")
icon = "09d";
if (icon == "13n")
icon = "13d";
if (icon == "50n")
icon = "50d";
icon = icons.indexOf(icon);
icon = conditions[icon];
document.getElementById("test").innerHTML = "<canvas id=\"" + icon + "\"></canvas>";
for(i = conditions.length; i--; )
skycons.set(conditions[i], conditions[i]);
skycons.play();
});
我简化了可能的图标代码,并删除了2个Skycon条件(雨夹雪和风),以更好地匹配Openweathermap API的图标代码。