gpt4 book ai didi

javascript - 将变量从一个 ajax 调用传递到另一个 ajax 调用

转载 作者:行者123 更新时间:2023-11-28 18:31:34 25 4
gpt4 key购买 nike

我有这个codepen Localweather App我创建了两个函数。

<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 + "&#176;C");
$('#wind').html(tempF + "&#176;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 函数,它接受一个地点并返回该地点的天气对象。我还有一个 getLocation 函数,我想根据 ip 返回我的城市(是的,我知道它不准确,但它是我想使用的)。

如果我对城市进行硬编码,它就可以工作。但尝试使用 getLoction 函数中的 city 变量是行不通的。我猜测这与异步有关,但我认为通过在 getLoction 函数中使用回调,它将返回“城市”,该“城市”将“然后”传递到 getWeather 中。还是我的想法全错了?

最佳答案

您需要使用(嵌套)回调,因为您需要等待 AJAX 调用的异步响应。

您的浏览器不会等待异步函数完成并继续运行到下一条语句,这就是您的代码中未定义 city 的原因 - 因为在您的代码中 getLocation仅当 getJSON 时返回值完成。

如果你的函数看起来像这样,你会得到一个返回值,但不是你想要的(所以不要使用下一个代码片段,它只是为了解释而存在)。

function getLocation() {
$.getJSON('http://ipinfo.io', function(data) {
return data.city; // this will be ignored, because the browser will jump to the next statement
});
return "XXX"; // <- this will be returned, because the browser will not wait for async functions to finish
}

在下面的示例中,我们将函数作为参数传递给 getLocation 。参数名称为callback我们用data来调用这个函数参数时$.getJSON('http://ipinfo.io'完成了。

从这个数据参数中我们可以提取city然后调用getWeather .

注意如何getLocation不再返回任何值,而是传递 data回调的参数(或者您可以在 city 中提取 getLocation,然后将 city 传递给回调)。

  $(document).ready(function() {

getLocation(function(data) {
var city = data.city;
getWeather(city).then(function(data) {
// ...
});
});
});

function getLocation(callback) {
$.getJSON('http://ipinfo.io', function(data) {
callback(data);
});
}

function getWeather(place) {
return $.getJSON('http://api.openweathermap.org/data/2.5/weather?q=' + place + '&units=imperial&APPID=90d625c068e3f3d7818b9e4237871e21');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>

关于javascript - 将变量从一个 ajax 调用传递到另一个 ajax 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37884474/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com