(Ajax) 在另一个 ajax 请求的 succes 里面的代码之后执行一个 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

})

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章