我遇到了ajax/promise的问题。我总共有两个ajax请求,第二个ajax调用依赖数据由第一个ajax调用返回。如何用承诺链接两个ajax请求
我的第一个ajax调用查找#search的纬度,经度和国家代码。 我的第二个ajax调用查找该城市的天气,但API URL取决于我的第一个ajax调用返回的纬度,经度和国家代码。所以第二个Ajax调用在第一个Ajax调用完成之前无法启动。
我的逻辑在于var ajax1被分配了一个promise,而var ajax2在ajax1.then()检查ajax1的promise被解析后启动。然后ajax2运行并返回另一个承诺。最后,ajax2.done在检查ajax2的承诺解决后启动,然后启动我的successWeatherFunction()。
我的问题是,ajax2.done不能正常工作,因为console.log(“test”)没有显示在控制台上。两个较早的console.logs,console.log(info)和console.log(weatherApiUrl)正在工作。
谢谢!
$("#search").keypress(function(event) {
if (event.which === 13) {
var searchCity = $("#search").val();
var jsonURL = "http://autocomplete.wunderground.com/aq?query=" + searchCity + "&cb=?"
var ajax1 = $.getJSON(jsonURL);
var ajax2 = ajax1.then(function(data) {
var info = [];
info.push(data["RESULTS"][0]["name"]);
info.push(data["RESULTS"][0]["c"]);
info.push(data["RESULTS"][0]["lat"]);
info.push(data["RESULTS"][0]["lon"]);
console.log(info);
var searchLat = info[2];
var searchLng = info[3];
var countryCode = info[1];
if (countryCode === "US") {
var weatherApiUrl = "https://api.forecast.io/forecast/{APIKEY}/" + searchLat + "," + searchLng + "?exclude=minutely" + "&callback=?";
} else {
var weatherApiUrl = "https://api.forecast.io/forecast/{APIKEY}/" + searchLat + "," + searchLng + "?exclude=minutely" + "?units=si" + "&callback=?";
console.log(weatherApiUrl);
}
return $.getJSON(weatherApiUrl);
});
ajax2.done(function(data){
console.log("test");
successCityWeather(data);
});
添加一些错误检查...'ajax2.catch(函数(ERR){执行console.log(ERR);})有(......你做功能...);' –
http://jsfiddle.net/arunpjohny/pkbfn5bt/1/ –
just sayin,''?exclude = minutely“+”?units = si“'对我来说看起来像一个无效的URL部分 – Bergi