javascript - (Ajax)在另一个 ajax 请求(而不是它内部)的代码成功之后执行一个 ajax 请求
问题描述
我有两个 Ajax 请求,第一个在 each() 内部,第二个在每个外部。问题是第一次请求成功里面的代码很重要,应该在第二次Ajax请求之前执行。
执行代码后,第一个 Ajax 请求被发送到服务器,但它的成功应该只在执行第二个 ajax 请求之后执行。
执行顺序:
first ajax
second ajax
success of first ajax
success of second ajax
有什么方法可以让第二个 ajax 等到第一个成功结束后再执行?
$(document).on("change",
".jsQuestionType",
function() {
// alert("The dropdown has been changed.");
var dropdownList = $(this);
var optionTypeId = $(dropdownList).val();
//get the jsQuestionSection
var question = $(dropdownList).parent().parent().parent();
//get the list of jsQuestionOptions
var questionOptions = $(dropdownList).parent().parent().parent().find(".jsQuestionOptions");
// loop in all questionOptions of the selected question
$(questionOptions).each(function(i, e) {
//alert($(e).find("input.jsInputName").attr("questionOptionsId"));
var optionId = $(e).find("input.jsInputName").attr("questionOptionsId");
$.ajax({
url: "/api/QuestionOptions/" + optionId,
method: "DELETE",
success: function(data) {
$(e).remove();
}
});
});
//End loop
var questionId = $(question).find("input.jsInputName").attr("questionId");
// if (questionOptions.length == 0) {
// create the new option using the value sent by dropdown
$.ajax({
url: "/api/QuestionOptions/" + optionTypeId + "/" + questionId,
method: "POST",
success: function(data) {
alert(data);
var d = data;
}
});
//}
});
解决方案
您可以在循环中创建一个请求承诺数组,并$.when
在所有先前的请求都解决后用于在循环外调用 ajax,如果这是您想要完成的
var requests = $(questionOptions).map(function(i, e) {
var optionId = $(e).find("input.jsInputName").attr("questionOptionsId");
// return ajax promise
return $.ajax({
url: "/api/QuestionOptions/" + optionId,
method: "DELETE",
success: function(data) {
$(e).remove();
}
});
}).get();
$.when.apply($, requests).then(function(){
// all the above requests completed
// do next request
})
推荐阅读
- jmeter - 无法在 Jmeter 中的聚合结果生成的 csv 报告中获取错误百分比列
- antd - antd Select 灯塔评分失败:[aria-*] 属性没有有效值
- hangouts-chat - 谷歌聊天自动回复机器人
- c++ - 难以设置和测试对象属性
- c++ - 如何在 C++ 中通过 reg 检查日期格式?
- firebase - Firebase Firestore 对“where”快照侦听器查询的计费方式如何?
- mysql - “group by”中最长字符串的ID
- r - 接收错误:“未知随机参数”,在 mlogit() [随机参数 logit 模型] 中定义 rpar 时
- google-analytics-4 - GA4:是否可以为 view_search_result 等自动事件添加自定义参数?
- android - Android 可组合,BasicCodelabTheme 显示错误