当AJAX调用完成时重置Bootstrap加载状态按钮

Reset Bootstrap loading state button when AJAX call is completed

本文关键字:Bootstrap 加载 状态 按钮 AJAX 调用 完成时      更新时间:2023-09-26

我有一个简单的AJAX请求,我想知道是否有可能将加载状态按钮与我的请求相结合。是否有可能使按钮重置为默认值时,请求完成,而不是选择例如5秒前重置为现在?

加载状态按钮

$("button").click(function() {
    var $btn = $(this);
    $btn.button('loading');
    // simulating a timeout
    setTimeout(function () {
        $btn.button('reset');
    }, 1000);
});

AJAX请求

  $(function () {
    $('form').on('submit', function (e) {
      e.preventDefault();
      $.ajax({
        type: 'POST',
        dataType:'html',
        url: '/m/core/_processEditEntry.php',
        data: $('form').serialize(),
        success: function () {
          $(".message").fadeIn(0);
          $(".message").delay(5000).fadeOut('slow');
        }
      });
    });
  });

最好将代码保存在同一个地方。删除单击处理程序并将以下行添加到ajax调用中:

  $(function () {
    $('form').on('submit', function (e) {
      //save button so we can use later
      var my_button = $(this).find("button");
      //give button loading state
      my_button.button('loading');
      e.preventDefault();
      $.ajax({
        type: 'POST',
        dataType:'html',
        url: '/m/core/_processEditEntry.php',
        data: $('form').serialize(),
        success: function () {
          //reset state
          my_button.button('reset');
          $(".message").fadeIn(0);
          $(".message").delay(5000).fadeOut('slow');
        }
      });
    });
  });

当按钮被点击时,你可以添加一个带有类的span

  if ($(this).is(".btn, .page-link, .df-link")) {
              // disable button
              $(".btn").prop("disabled", true);
              // add spinner to button
              $(this).html(
                `<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> ` + $(this).text()
              );
          }

,然后在Ajax中完全删除该元素:

complete: function(response) {
                $(".btn").prop("disabled", false);
                $(".spinner-border").remove();
            }