【发布时间】:2016-08-17 15:31:12
【问题描述】:
我正在尝试在第二个 ajax 调用中使用第一个 ajax 调用的值。我正在使用下面的代码结构。出于某种原因,第二次调用为userLocation variable 返回undefined。如何重构我的代码,以便可以在第二个 ajax 调用的 url 中使用第一个 ajax 调用的 userLocation 值?
var userLocation;
function getUserLocation() {
$.ajax({
url: 'https://www.example.com/location.json',
success: function(response) {
userLocation = response.coordinates;
}
});
}
function getCurrentWeather() {
$.ajax({
url: 'https://www.example.com/weather' + userLocation + '.json',
success: function(response) {
console.log(response);
}
});
}
$(document).ready(function() {
$.when(
getUserLocation()
).done(
getCurrentWeather()
)
});
更新 1: 感谢下面提供的答案,我已经能够重构我的代码。现在从第一个 ajax 调用收到的值可以在第二个 ajax 调用中使用。这是更新的代码:
var userLocation;
function getUserLocation() {
return $.ajax('https://www.example.com/location.json')
.then(function(response) {
return JSON.parse(response);
}).then(function(json) {
// data from the location.json file is available here
userLocation = json.coordinates;
})
}
function getCurrentWeather() {
return $.ajax('https://www.example.com/weather' + userLocation + '.json');
}
getUserLocation().then(getCurrentWeather).then(function(data) {
// data from the weather(userLocation).json file is available here
});
【问题讨论】:
标签: javascript jquery ajax asynchronous promise