Laravel 5.2和AJAX - 重定向后显示成功消息

Jaz*_*bot 3 ajax laravel bootstrap-modal laravel-5.2

我正在L5.2中创建一个CRUD系统,并使用Bootstrap Modal来显示表单.我使用了BootFormsLaravel Bootstrap Modal Form来验证表单并在Modal中显示错误消息而不关闭它.

基本上我在同一页面上的模态中打开添加/编辑表单,表单验证在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();
    }
});
Run Code Online (Sandbox Code Playgroud)

控制器:

public function store(CustomerRequest $request)
{
    Customer::create($request->all());

    return redirect('customers')
        ->with('message', 'New customer added successfully.')
        ->with('message-type', 'success');
}
Run Code Online (Sandbox Code Playgroud)

查看:(显示成功消息)

@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
Run Code Online (Sandbox Code Playgroud)

你可以看到AJAX只是重新加载页面成功,我希望它重定向到Controller函数中指定的页面并显示该成功消息.

Jus*_*and 12

您正在从响应返回HTTP重定向,这不适用于AJAX请求.诸如浏览器之类的客户端将能够拦截并使用标题信息,然后重新加载页面.

相反,对于您的特定问题,请考虑:

https://laravel.com/docs/5.2/session#flash-data

public function store(CustomerRequest $request)
{
    Customer::create($request->all());

    $request->session()->flash('message', 'New customer added successfully.');
    $request->session()->flash('message-type', 'success');

    return response()->json(['status'=>'Hooray']);
}
Run Code Online (Sandbox Code Playgroud)

现在,HTTP/200 OK您的AJAX收到的响应将会执行location.reload,并且闪存的会话数据将可供视图使用.