如何解决Bootstrap Spinner 在表单提交和 API 调用竞争后不会停止
我正在使用引导程序,并且在提交表单时尝试设置微调器。我可以在提交表单时让微调按钮旋转,但是在提交后它只会继续旋转。我已经查看了所有内容,但似乎无法弄清楚如何在 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...`
);
});
});
Ajax 调用
$(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();
});
});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。