【问题标题】:How to call a function after another ends?如何在另一个结束后调用一个函数?
【发布时间】:2021-09-27 10:34:13
【问题描述】:

打开模态框后我正在做一些功能。 RefreshBirths() 函数需要 motherIdfatherId 来自 getDictionaryMother()getDictionaryFather() 函数(这些在页面上呈现 my mothersfather 然后我可以得到refreshBirths() 函数中的值)。

我检查了refreshBirths() 太早使用我的 id,所以最后有未定义的 id。

我检查了在mother/father 方法中的.done 部分中调用我的refreshBirths() 函数,它解决了我的问题,但我更喜欢在代码的指定部分中明确地这样做。

这不能解决,但我想在那儿做这个:

  $('#create-modal').on('shown.bs.modal', function() {
  refreshBreeds();
  getDictionaryMother();
  getDictionaryFather();
  $.when(getDictionaryFather()).done(function() {
         refreshBirths();
  });
});

这里修复了,但我更喜欢在另一个地方调用该方法

    function getDictionaryMother() {
    $.ajax({
            url: "/admin/api/dictionary/" + "ANIMAL_MOTHER",
            type: "GET",
            dataType: "json"
        })
    .done(function(response) {
           $('#mother-create').empty();
           $('#mother').empty();
           response.forEach(function(mother){
                $('#mother-create').append('<option value='+ mother.id +'> '+ mother.value +' </option>');
                $('#mother').append('<option value='+ mother.id +'> '+ mother.value +' </option>');
           });

refreshBirths();


    })
    .fail(function(jqxhr, textStatus, errorThrown) {
        displayErrorInformation("Cannot get dict: " + name + " due to: " + jqxhr.responseText);
    });
}

【问题讨论】:

  • 您可以添加一个回调函数作为参数,然后在方法中最后调用它,即在处理来自 ajax 请求的响应之后。

标签: javascript html jquery ajax bootstrap-5


【解决方案1】:

您可以在 Ajax 请求上使用 .then() 方法或 .when()。

【讨论】:

  • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
猜你喜欢
  • 1970-01-01
  • 2022-11-29
  • 2012-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-01
  • 2023-03-03
  • 1970-01-01
相关资源
最近更新 更多