javascript - 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;
}
});
});
解决方案
当有人单击按钮时使用此代码,我想显示加载器,但由于在 jquery ajax 中使用 async:false 而没有显示。它在完成 ajax 成功后显示加载程序。
这就是不 async: false
推荐使用的原因。
它完全锁定了 UI。
如果您想在发出请求时做任何事情,请不要使用async: false
.
相反:始终阻止默认行为,然后(如果需要)在异步操作完成后重新触发它。
推荐阅读
- javascript - Tryint 在 JavaScript 中将 BigInt 转换为十六进制
- caching - 在“延迟值表”中:每一级缓存的延迟值是否包括上一级缓存的访问?
- c# - 尝试更新嵌套数组时出现 Mongo 错误:未找到标识符的数组过滤器
- python - 如何从列表中创建 x,y 对
- java - 找不到以下类: - android.support.v7.widget.RecyclerView
- c# - 在 Unity 2D 编辑器中,即使我告诉它,我的 UI 文本也没有改变
- flutter - 有没有办法从firestore中删除文件夹?
- python - 从日期序数数组设置日期刻度标签
- c++ - 带有 char[] 字段的 POD 结构的 constexpr 构造
- android - 第一次如何在新计算机上设置现有的 React-Native 项目?