我嘗試在另一個(與.then)之內嵌套一個ajax請求,所以我可以使用第二個Ajax請求中的第一個數據。在這種情況下,我想使用第一個Ajax調用的座標到第二個Ajax請求(地圖座標)。 變量是格子和長。依賴於來自另一個請求的數據的Ajax請求
$(document).ready(function(){
$('#submitWeather').click(function(){
var city= $("#city").val();
var latt, long;
if(city !=''){
$.ajax({
url:'http://api.openweathermap.org/data/2.5/weather?q=' + city + "&units=metric" + "&APPID="....",
type: "GET",
dataType: "jsonp",
success: function(data){
console.log(data);
var widget = show(data);
$("#show").html(widget);
latt = coord.lat;
long = coord.lon;
}
}).then($.ajax({
url:'https://maps.googleapis.com/maps/api/js?key="..."&callback=initMap',
type: "GET",
dataType: "jsonp",
success: function initMap() {
var uluru = {lat: +latt+, lng: +long+};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: uluru
});
var marker = new google.maps.Marker({
position: uluru,
map: map
});
}
});
}else{
$("#error").html("<div class='alert alert-danger text-center'> The field cannot be empty, please enter a city! </div>");
}
});
});
只是把第二個函數放在第一個函數的成功函數中。 – sideroxylon
[JavaScript承諾:介紹](https://developers.google.com/web/fundamentals/getting-started/primers/promises) – Andreas