首页 > 解决方案 > jQuery ajax async false 修改页面中的 html

问题描述

需要帮助来解决问题,陷入困境并投入了大量时间。

我在这里做什么,

我正在使用 post 传统方法提交表单,但在提交表单之前,我正在使用上面的 jquery ajax 代码进行一些操作,并且工作正常。

当有人单击按钮时使用此代码,我想显示加载器,但由于async:false在 jquery ajax 中使用而没有显示。它在完成 ajax 成功后显示加载程序。

在这种情况下,似乎没有发生任何事情,并且在单击按钮后没有加载程序工作。

显示加载器的 Html 代码是这样的

<button type="submit" id="submit" class="btn btn-primary add_campaign_handler_button" name="submit">
    <i class="fa fa-spinner fa-spin" id="url_button_loader" style="display:none;"></i>
    Save Settings
</button>

jQuery:

$("#submit").click(function() {
  $('#url_button_loader').css('display', 'inline-block');
  var submit_flag = "yes";
  var where_to_appear_for_db = "";
  /* create custom post url */
  var post_name = $("#custom_post_slug").val();
  if (post_name != "") {
    var data = {
      data: post_name
    };
    $.ajax({
      url: ajaxurl,
      type: 'POST',
      data: {
        'action': 'create_custom_post_url',
        'data': data
      },
      beforeSend: function() {
        $('#url_button_loader').css('display', 'inline-block');
      },
      async: false,
      success: function(response) {
        if (response == "exists") {
          Swal.fire({
            type: 'error',
            title: 'Oops...',
            text: wpmlBackObj.smart_link_exists
          });
          $("#retargeting_url").val("");
          submit_flag = "no";
          $('html,body').animate({
            scrollTop: 0
          });
          return;
        }
        $("#tooltip_error").hide();
        $("#campaign_post_id_hidden").val(response);
        get_retargeting_url(response, "");
      }
    });
    if (submit_flag == "yes") {
      return true;
    } else {
      $('#url_button_loader').css('display', 'none');
      return false;
    }
  });
});

标签: javascriptphpjqueryajax

解决方案


当有人单击按钮时使用此代码,我想显示加载器,但由于在 jquery ajax 中使用 async:false 而没有显示。它在完成 ajax 成功后显示加载程序。

这就是 async: false推荐使用的原因。

它完全锁定了 UI。

如果您想在发出请求时做任何事情,请不要使用async: false.

相反:始终阻止默认行为,然后(如果需要)在异步操作完成后重新触发它。


推荐阅读