簡體   English   中英

在另一個函數內部運行函數,但僅在ajax完成之后

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

我有一個在另一個函數內部運行的函數,但有時似乎我對服務器的ajax調用在調用該函數之前並未完成運行。

    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);
      })
    }

作為快速解決方案,您可以使用async: false進行.ajax調用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);
}

解決方案2:您可以在jQuery中使用.when

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);
}

嘗試從成功回調中調用getPermissions()

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);
    });
 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM