Pio*_*cki 5 javascript ajax jquery asynchronous promise
我试图在第二个ajax调用中使用第一个ajax调用的值.我正在使用下面的代码结构.出于某种原因,第二个调用返回undefined的userLocation variable.我怎么能重构我的代码,以便第一个ajax调用的userLocation值可以在第二个ajax调用的url中使用?
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()
)
});
Run Code Online (Sandbox Code Playgroud)
更新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
});
Run Code Online (Sandbox Code Playgroud)
jQuery的ajax返回promises,你可以使用:
function getUserLocation() {
return $.ajax('https://www.example.com/location.json'); // note the `return`
}
function getCurrentWeather(userLocation) {
return $.ajax('https://www.example.com/weather' + userLocation + '.json');
}
getUserLocation().then(getCurrentWeather).then(function(data) {
// location data here
});
Run Code Online (Sandbox Code Playgroud)
或者,更冗长
getUserLocation().then(function (user) {
return getCurrentWeather(user);
}).then(function(data) {
// location data here
});
Run Code Online (Sandbox Code Playgroud)
更好的解决方案是将其作为单个调用而不是两个调用,因为大量的AJAX调用会降低应用程序的速度 - 尤其是在带宽有限的移动设备上.
这是一种基于回调的方法,可能不如基于promise的方法(例如,使用错误处理) - 但我觉得我们应该为完整性而显示它.您可以在此主题中阅读有关常规解决方案的信息.
function getUserLocation(callback) {
$.ajax('https://www.example.com/location.json', callback)
}
function getCurrentWeather(userLocation, callback) {
$.ajax('https://www.example.com/weather' + userLocation + '.json', callback);
}
getUserLocation(function(user) {
getCurrentWeather(user, function(weather) {
console.log("Got weather", weather);
});
});
Run Code Online (Sandbox Code Playgroud)