【发布时间】:2019-11-01 16:52:03
【问题描述】:
我正在尝试实现一个 ajax 表单,以检查在出现错误时应该在哪里显示 toast 消息。这是我想触发的 toast 消息部分的一部分,看起来像
@if ($errors->any())
<div class="alert alert-danger alert-dismissable fade show {{ session()->get('dismiss', '') }}" data-auto-dismiss="2000">
<i class="fas fa-times-circle toast-icon"></i>
<div class="toast-message">{{ $errors->has('message') ? $errors->first('message', ':message') : __('The given data was invalid.') }}</div>
<i class="fal fa-times close" data-dismiss="alert" aria-label="Close"></i>
</div>
@endif
然后,这个文件被包含在一个 div 中,我使用 <div class="alert-container">@include('frontend.layout.toast-message')</div> 放置在我的 html 正文中
在我的 js 方面,我正在调用的 ajax 函数。
$('#signup_form').submit(function(e) {
e.preventDefault();
$.ajax({
method: "POST",
url: $('#signup_form').attr('action'),
data: new FormData($('#signup_form')[0]),
processData: false,
contentType: false,
cache: false,
beforeSend: function (xhr) {
$(this).find('button').prop('disabled', true);
$.each($('.form-group.is-invalid .message'), function () {
$(this).text('');
});
$.each($('.form-group.is-invalid'), function () {
$(this).removeClass('is-invalid');
});
}
}).done(function (response) {
if (response.success == true) {
///
}
})
.fail(function(jqXHR) {
if (jqXHR.responseJSON) {
//prompt for alert message
var alertContainer = $('.alert-container');
alertContainer.find('.toast-message').text(jqXHR.responseJSON.message).addClass('show');
alert(jqXHR.responseJSON.message);
//go through each input to see which ones are within the error
$.each(jqXHR.responseJSON.errors, function (field, message) {
var element = $('#'+ field);
element.parents('.form-group').addClass('is-invalid');
element.parents('.form-group').find('.message').text(message).show();
});
}
$(this).find('button').prop('disabled', false);
})
});
警报返回我应该在我的 toast 消息中收到的消息,但是 toast 没有显示。最好知道代码中出了什么问题,或者我是否应该以其他方式解析错误消息?
【问题讨论】:
标签: javascript jquery ajax laravel toast