我需要从 AJAX 响应传递数据。代码如下:
function getLocation() {
$.get('https://ipinfo.io/json', function (data) {
console.log(data);
$('.test').html('<h2>Your location is: ' + data.city + '.</h2>');
});
}
getLocation();
它工作正常,但我想使用 data.city
作为变量,我可以将其传递给其他 api 请求,以获取该城市的温度。我刚刚开始 js/jQuery 开发,所以任何帮助将不胜感激。
最佳答案
您处于异步上下文中,因此不能简单地使用返回值。一种方法是通过提供相应的回调函数来链接操作。
var self = this;
function getLocation(callback) {
$.get('https://ipinfo.io/json', function (data) {
console.log(data);
$('.test').html('<h2>Your location is: ' + data.city + '.</h2>');
callback.call(self, data.city);
});
}
function getTemperature(location) {
//do another AJAX call here to get temperature and modify your DOM
}
getLocation(getTemperature);
关于javascript - 使用 AJAX 响应作为函数外部的 var,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43522180/