【问题标题】:Run function inside of another function, but only after ajax has finished在另一个函数内运行函数,但仅在 ajax 完成后
【发布时间】:2015-04-17 17:18:41
【问题描述】:

我有一个在另一个函数内部运行的函数,但有时似乎我对服务器的 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);
      })
    }

【问题讨论】:

  • 嗯,我想你可能把回调搞混了。您的 function(data) 回调首先被调用,然后是您的 done 回调。为什么将它们放在两个不同的回调中?在.each() 之后运行getPermissions ?

标签: javascript jquery ajax


【解决方案1】:

作为一种快速解决方案,您可以使用async: false 拨打.ajax 电话

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

【讨论】:

    【解决方案2】:

    尝试从成功回调中调用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);
        });
     }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-28
      • 1970-01-01
      • 2013-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-18
      相关资源
      最近更新 更多