简体   繁体   中英

Run function inside of another function, but only after ajax has finished

I have a function that is run inside of another function, but sometimes it seems my ajax call to the server isn't finished running before it calls the function.

    function getPlans(row, user, id, type) {
      $.get( "/plans/" + user + "/" + id + "/" + type + "", function(data) {
        $("#permissions_" + row + "_plan_type").empty();
        $(data).each(function(i, e) {
          $("#permissions_" + row + "_plan_type").append("<option>" + e + "</option>");
        })
      }).done(function() {
        getPermissions(row, user, type);
      })
    }

As a quick solution you can make an .ajax call with async: false

 function getPlans(row, user, id, type) {
  $.ajax({
    url:"/plans/" + user + "/" + id + "/" + type + "",
    type: 'GET',
    dataType: "json",
    contentType: "application/json; charset=utf-8",
    success: function(data) {
        $("#permissions_" + row + "_plan_type").empty();
        $(data).each(function(i, e) {
          $("#permissions_" + row + "_plan_type").append("<option>" + e + "</option>");
        })
      },
      async:false // make synchronous
  });

  getPermissions(row, user, type);
}

Solution 2: You can use .when from jQuery.

function getPlans(row, user, id, type) {
    var dfd = $.Deferred();
    $.when( $.get( "/plans/" + user + "/" + id + "/" + type + ""))
        .done(function(data) {
            $("#permissions_" + row + "_plan_type").empty();
            $(data).each(function(i, e) {
              $("#permissions_" + row + "_plan_type").append("<option>" + e + "</option>");
            })
        });

    getPermissions(row, user, type);
}

Try calling getPermissions() from success callback.

function getPlans(row, user, id, type) {
    $.get( "/plans/" + user + "/" + id + "/" + type + "", function(data) {
        $("#permissions_" + row + "_plan_type").empty();
        $(data).each(function(i, e) {
          $("#permissions_" + row + "_plan_type").append("<option>" + e + "</option>");
        });
        getPermissions(row, user, type);
    });
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM