我需要从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);
这是一个异步回调。因此,如果您以后要使用它,例如要进行另一个Ajax调用,则应在回调中进行下一个呼叫:
function getLocation() {
$.get('https://ipinfo.io/json', function (data) {
console.log(data);
$('.test').html('<h2>Your location is: ' + data.city + '.</h2>');
// Use your data here for another AJAX call
$.get('https://example.com/test?city=' + data.city, function () {});
});
}
getLocation();
您不妨以后寻找以更优雅的方式处理异步代码的承诺。https://developer.mozilla.org/pl/docs/web/javascript/Reference/global_objects/promise