【问题标题】:Laravel 5.2 & AJAX - Display success message after redirectLaravel 5.2 & AJAX - 重定向后显示成功消息
【发布时间】:2016-10-09 23:08:02
【问题描述】:

我正在 L5.2 中创建一个 CRUD 系统,并正在使用 Bootstrap Modal 来显示表单。我使用BootFormsLaravel Bootstrap Modal Form 来验证表单并在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 函数中指定的页面并显示该成功消息。

【问题讨论】:

    标签: ajax laravel laravel-5.2 bootstrap-modal


    【解决方案1】:

    您正在从响应中返回 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,并且刷新的会话数据将可用于视图。

    【讨论】:

    • 你拯救了我的一天,太棒了。
    • 您是否总是必须返回响应才能将数据放入会话中?因为我只写了$request-&gt;session()-&gt;flash('message-type', 'success');这一段代码,并没有成功。这是为什么呢?
    猜你喜欢
    • 2016-09-19
    • 2016-07-15
    • 1970-01-01
    • 1970-01-01
    • 2021-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多