私はこのコードを持っていますLocalweather App私は2つの関数を作成しました。別のajax呼び出しから変数を渡す
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
$(document).ready(function() {
var city = "Newcastle";
city = getLocation();
//set city to location from function;
console.log ("city undefined?" +city);
//this is undefind, why?
getWeather(city).then(function(data) {
console.log(data);
var weatherType = data.weather[0].description;
var weatherId = data.weather[0].id;
var tempF = Math.round(data.main.temp);
var tempC = Math.round((tempF - 32)/1.8);
var wind = data.wind.speed;
var name = data.name;
console.log(weatherType);
$('#weather').html(weatherType);
$('#temp').html(tempC + "°C");
$('#wind').html(tempF + "°F");
$('#icon').html(weatherId);
$('#location').html(name);
})
});
function getLocation() {
$.getJSON('http://ipinfo.io', function(data) {
console.log("data" + data);
city = data.city;
console.log("city" + city);
return city;
})
}
function getWeather(place) {
return $.getJSON('http://api.openweathermap.org/data/2.5/weather?q=' + place + '&units=imperial&APPID=90d625c068e3f3d7818b9e4237871e21');
}
</script>
場所に取り、その場所の天気オブジェクトを返しますgetWeather機能。私はまた、IPに基づいて私の都市を返すようにしたいgetLocation関数を持っています(はい、私は正確ではないが、私が使いたいものを知っています)。
都市をハードコードすると機能します。 しかし、getLoction関数から都市変数を使用しようとしても動作しません。 私はそれが非同期であったと推測していますが、getLoction関数でコールバックを使用すると、 'city'が返され、getWeatherに渡されます。 私の考えは間違っていますか?
コンソールで何を得るのですか。ログを呼び出す? –
(ネストされた)コールバックを操作する必要があります。 –
メソッド呼び出しを連鎖させる必要があります。受信したデータでgetLocationを呼び出すgetWeatherが成功すると、ここでajaxコールバックの仕組みを見てください:http://api.jquery.com/jquery.getjson/ –