我在L5.2中创建一个CRUD系统,并使用Bootstrap Modal来显示表单。我已经使用BootForms和Laravel Bootstrap Modal Form验证窗体并在Modal中显示错误消息而不关闭它。Laravel 5.2&AJAX - 在重定向后显示成功消息
基本上我打开在同一页上的模式内添加/编辑表单,表单验证在Modal中完成,一旦一切正常,数据将被插入到数据库中并且模式关闭。之后,页面刷新并显示更新的数据。
一切工作正常,除了成功的情况下,我无法在我的网页上显示成功消息。
以下是我的代码:
AJAX
$.ajax({
type: "POST",
url: url,
data: data,
dataType: 'json',
cache: false,
contentType: contentType,
processData: false
// Response.
}).always(function(response, status) {
// Reset errors.
resetModalFormErrors();
// Check for errors.
if (response.status == 422) {
var errors = $.parseJSON(response.responseText);
// Iterate through errors object.
$.each(errors, function(field, message) {
console.error(field+': '+message);
var formGroup = $('[name='+field+']', form).closest('.form-group');
formGroup.addClass('has-error').append('<p class="help-block">'+message+'</p>');
});
// Reset submit.
if (submit.is('button')) {
submit.html(submitOriginal);
} else if (submit.is('input')) {
submit.val(submitOriginal);
}
// If successful, reload.
} else {
location.reload();
}
});
控制器:
public function store(CustomerRequest $request)
{
Customer::create($request->all());
return redirect('customers')
->with('message', 'New customer added successfully.')
->with('message-type', 'success');
}
查看:(显示成功消息)
@if(Session::has('message'))
<div class="alert alert-{{ Session::get('message-type') }} alert-dismissable">
<button aria-hidden="true" data-dismiss="alert" class="close" type="button">×</button>
<i class="glyphicon glyphicon-{{ Session::get('message-type') == 'success' ? 'ok' : 'remove'}}"></i> {{ Session::get('message') }}
</div>
@endif
你可以看到成功的情况下AJAX只是重新加载页面,我希望它重定向到Controller函数中指定的页面并显示该成功消息。
你已经救了我的一天,布拉沃。 – Jazzbot
你是否总是必须返回响应才能将数据放入会话中?因为我只写了这段代码'$ request-> session() - > flash('message-type','success');'并且它不工作。为什么? – shigg