我对嵌套ajax调用有特定的要求。我试图在一个ajax调用成功的内部设置一个全局可访问变量,并且在另一个ajax调用成功的内部调用此ajax调用。最终,父级ajax调用的父级成功方法利用全局变量执行进一步的操作。问题在于全局变量的值始终保持空白。如果我将第二个ajax请求作为async:false;起作用。但是此解决方案首先破坏了使用ajax的目的。
让我分享一个小的示例代码来说明我的问题:
//global variables
var xURL = "https://sampleurl.com";
var glblID = "";
//first ajax call
$.ajax({
url: url1,
data: data1,
type: "POST",
contentType: "application/json",
success: function (msg) {
//some js code here
//second ajax call
FetchID();
//more js code here
if(glblID != "")
{
window.location.href = xURL + "?id=" + glblID
}
else
{
window.location.href = xURL;
}
}
});
function FetchID()
{
$.ajax({
url: url2,
data: data2,
type: "POST",
contentType: "application/json",
success: function (data) {
glblID = data.d;
}
});
}
答案 0 :(得分:1)
从
的属性,方法和行为jQuery 1.5
开始实施Promise
接口,为他们提供全部Promise
//first ajax call
$.ajax({
url: url1,
data: data1,
type: "POST",
contentType: "application/json"
}).then(function (msg) {
//second ajax call
FetchID().then((data) => {
var glblID = data.d;
if (glblID != "") {
//do something with glblID
} else {
//do something else
}
});
});
function FetchID() {
return $.ajax({
url: url2,
data: data2,
type: "POST",
contentType: "application/json"
});
}