javascript - 提交表单和 API 调用竞争后,Bootstrap Spinner 不会停止
问题描述
我正在使用引导程序,并且正在尝试在提交表单时设置微调器。我可以在提交表单时让微调器按钮旋转,但是在提交后它只会继续旋转。我已经看了一遍,但似乎无法弄清楚一旦 API 调用完成后如何让它停止。我如何在提交表单时让它旋转,一旦 API 调用完成就停止并在 API 调用完成后再次返回可用按钮?
html代码
<form id="form_id" name="form_id" class="form_id" method="POST" >
<div class="input-group-append">
<button type="submit" id="btnFetch" class="btn btn-primary mb-2">Submit</button>
</div>
</form>
JS代码
$(document).ready(function() {
$("#btnFetch").click(function() {
$(this).prop("disabled", true);
$(this).html(
`<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>Loading...`
);
});
});
阿贾克斯调用
$(document).ready(function() {
$('.form_class1').on('submit', function(event) {
$.ajax({
data : {
some_id: $('#some_id').val(),
},
type : 'POST',
url : '/ajax_request_url1'
})
.done(function(data) {
if (data.error) {
}
else {
// Do Processing here....
}
});
event.preventDefault();
event.stopImmediatePropagation();
});
});
解决方案
您可能会考虑重新组织一些事情以简化正在发生的事情。
- 创建单独的函数来处理微调器状态。
function startSpinner() {
// your code to make the spinner start
$("#btnFetch").prop("disabled", true);
$("#btnFetch").html(
`<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>Loading...`
);
}
function stopSpinner() {
// you code to make the spinner stop
// (i.e., return the button to its original state)
$("#btnFetch").prop("disabled", false);
$("#btnFetch").html('Submit');
}
- 在提交过程中的适当时间调用您的微调器函数。
$(document).ready(function() {
$('.form_class1').on('submit', function(event) {
// initiate spinner
startSpinner();
$.ajax({
data : {
some_id: $('#some_id').val(),
},
type : 'POST',
url : '/ajax_request_url1'
})
.done(function(data) {
// ...
})
.always(function(dataOrjqXHR, textStatus, jqXHRorErrorThrown) {
// do when complete, even on error
// stop the spinner
stopSpinner();
});
// should these be at the top?
event.preventDefault();
event.stopImmediatePropagation();
});
});
推荐阅读
- python - 使用python根据列对Excel工作表进行排序
- scala - 为什么部分应用函数在两个相似的场景中表现不同
- c++ - 布尔值通过引用传递,但我仍然在 cpp 中遇到编译错误
- ruby-on-rails - 如何按关联对记录进行排序?
- c - 是否有正确的方法来制作“打印消息并继续”宏?
- javascript - 如何为特定系列设置 Y 轴上的点高度
- postgresql - 将 csv.gzip 从 Google Storage 导入 CloudSQL
- ios - 无法将 URLString 存储在我的 Firebase 实时数据库中
- powershell - Get-Printer -AsJob 如何在错误时找到 ComputerName
- mysql - 如何解决此错误 - ERROR 1064 (42000): You have an error in your SQL syntax