Jquery - $.当不触发 ajax on done menthod 时



尝试使用 Jquery $ 基于前两个结果实现另一个 ajax 调用。当方法。基本上,所有三个 Ajax 都会根据结果在页面上填充轮播。因此,我选择$。何时进行连续检查。 但是在 Done(( 方法下没有调用第三个 Ajax,即使没有来自上述两个 API 或初始值零 (0( 的结果。不知道我是否错过了什么!

j查询:

let itemCat1Count = 0;
let itemCat2Count = 0;
$.when(
$.ajax({
url: "/webmethod/GetItemsCatOne",
type: "POST",
data: '',
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
if (typeof (data.ResponseObject) !== undefined && data.ResponseObject !== null) {
itemCat1Count = data.ResponseObject.Items.length;
// carousel inital codes
}
},
error: function (jqXHR, status, error) {}
}),
$.ajax({
url: "/webmethod/GetItemsCatTwo",
type: "POST",
data: '',
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
if (typeof (data.ResponseObject) !== undefined && data.ResponseObject !== null) {
itemCat2Count = data.ResponseObject.Items.length;
// carousel inital codes
}
},
error: function (jqXHR, status, error) {}
}),
).done(function (xhrSavedRings, xhrShoppingBagItems) {
if (itemCat1Count == 0 && itemCat2Count == 0) {
$.ajax({
url: "/webmethod/GetItemsSpecial",
type: "GET",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (jObject) {
console.log(jObject);
// carousel inital codes
},
error: function (jqXHR, status, error) {}
});
}
});

需要强调的几件事 -$.when()需要承诺作为论据。$.when没有权力知道您传递的功能何时完成或完成 来自$.when的官方文档 你有返回承诺或从你的 ajax 调用中返回一些东西。

这里它说的=>在多个延迟对象传递给jQuery.when()的情况下,该方法从一个新的"主"延迟对象返回承诺,该对象跟踪它已传递的所有延迟对象的聚合状态。

我已经从您正在进行的每个$.ajax调用中分配了一个 retrun 值。 $.when 将知道检查是否有来自返回的内容并得到解决,然后它将转到.done

运行下面的代码片段以查看控制台登录.done

let itemCat1Count = 0;
let itemCat2Count = 0;
function first() {
return $.ajax({
url: "/webmethod/GetItemsCatOne",
type: "POST",
data: '',
contentType: "application/json; charset=utf-8",
success: function(data) {
if (typeof(data.ResponseObject) !== undefined && data.ResponseObject !== null) {
console.log(data.ResponseObject.Items.length)
itemCat1Count = data.ResponseObject.Items.length;
// carousel inital codes
}
},
error: function(jqXHR, status, error) {}
});
}
function second() {
return $.ajax({
url: "/webmethod/GetItemsCatTwo",
type: "POST",
data: '',
contentType: "application/json; charset=utf-8",
success: function(data) {
if (typeof(data.ResponseObject) !== undefined && data.ResponseObject !== null) {
itemCat2Count = data.ResponseObject.Items.length;
// carousel inital codes
}
},
error: function(jqXHR, status, error) {}
});
}
$.when.apply(first(), second()).done(function() {
console.log("First and Second is done running - I am from done");
if (itemCat1Count == 0 && itemCat2Count == 0) {
return $.ajax({
url: "/webmethod/GetItemsSpecial",
type: "GET",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(jObject) {
console.log(jObject);
// carousel inital codes
},
error: function(jqXHR, status, error) {}
});
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

最新更新