问题描述
当我进行ajax调用时,将显示我的模态(options.beforeSend)。但是,当我收到ajax结果错误(options.error)时,我想隐藏此模式。我尝试过但没有成功。
Index.cshtml
@* Modal - load spin *@
<div class="modal fade" id="itemloader" tabindex="-1" role="dialog" aria-labelledby="ModalLabel2" aria-hidden="true" data-backdrop="static" data-keyboard="false">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title"></h5>
</div>
<div class="modal-body d-inline text-center">
<div class="spinner-border spinner-border-sm text-info" role="status">
<span class="sr-only small"></span>
</div>
<span class="far fa-dizzy fa-3x text-secondary" style="display:none;"></span>
<label id="ModalStatus">Loading...</label>
</div>
</div>
</div>
</div>
在发送之前,我切换/显示模式:
options.beforeSend = function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",$('input:hidden[name="__RequestVerificationToken"]').val());
// My modal (works fine)
$('#itemloader').modal('toggle');
$('#itemloader').modal('show');
};
options.success = function (data) {
if (data.idOrder!= null) {
window.location.href = "/app/order/order?Id=" + data.idOrder;
}
};
如果发生错误(从ModelState返回部分视图后无效),我正在尝试隐藏模式,但是我不能:
options.error = function (res) {
// When my modelState is not valid,return partial view with required messages (working fine)
$('#chkForm').html(res.responseText);
// But I can't hide the modal (does not work)
var modal = $("#itemloader");
modal.hide();
// hide modal (does not work)
$('#itemloader').modal('hide');
$('#itemloader').hide();
};
我尝试了模式上的关闭按钮,但也没有成功:
<button id="btnclosemodal" class="close" type="button" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
// Does not work
$('#btnclosemodal').click();
// Does not work
$("#btnclosemodal").trigger("click");
解决方法
如果请求失败,将调用
error
函数。我认为这里不会进入错误功能,因为它会正常返回部分视图。您可以使用f12并在“源”选项卡中对其进行调试。
相反,我认为您应该在成功函数中隐藏模式。
,您可以尝试在错误时切换模式,如下所示:
$('#itemLoader').modal('toggle');