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

6
我正在L5.2中创建一个CRUD系统,并使用Bootstrap Modal来显示表单。我使用 BootForms Laravel Bootstrap Modal Form来验证表单并在Modal内显示错误消息,而不关闭它。
基本上,我在同一页的Modal中打开添加/编辑表单,在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();
    }
});

控制器:

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只是重新加载页面,我希望它重定向到控制器函数中指定的页面并显示成功消息。
1个回答

20

您正在从响应中返回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']);
}

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


1
你救了我的一天,太棒了。 - Jazzbot
1
你是否总是需要返回响应才能将数据放入会话中?因为我只写了这一行代码 $request->session()->flash('message-type', 'success');,但它没有生效。这是为什么? - shigg

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接