(Ajax)在另一个ajax请求成功之后执行一个ajax请求(不在其中)

问题描述 投票:-1回答:1

我有两个Ajax请求,第一个在每个()内部,第二个在每个内部。问题是第一个请求成功的代码非常重要,应该在第二个Ajax请求之前执行。

执行代码后,第一个Ajax请求被发送到服务器,但只有在执行第二个ajax请求后才能执行。

执行顺序:

first ajax
second ajax
success of first ajax
success of second ajax

有没有办法让第二个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;
      }
    });

    //}

  });
javascript jquery ajax
1个回答
0
投票

您可以在循环中创建一个请求promise的数组,并使用$.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

})
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.