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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37723544/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 13:57:57  来源:igfitidea点击:

Laravel 5.2 & AJAX - Display success message after redirect

ajaxlaravellaravel-5.2bootstrap-modal

提问by Jazzbot

I'm creating a CRUD system in L5.2 and am using Bootstrap Modal to display forms. I've used BootFormsand Laravel Bootstrap Modal Formto validate forms and display error messages inside Modal without closing it.

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

Basically I'm opening Add / Edit forms inside a modal on same page, the form validation is done inside Modal and once everything is okay the data is being inserted in database and the modal closes. After that the page refreshes and shows updated data.

基本上我在同一页面上的模态内打开添加/编辑表单,表单验证在模态内完成,一旦一切正常,数据就会插入数据库中,模态关闭。之后页面刷新并显示更新的数据。

Everything is working fine, except in case of success I am not able to display a success message on my page.

一切正常,除非成功,否则我无法在我的页面上显示成功消息。

Following is my code:

以下是我的代码:

AJAX

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();
    }
});

Controller:

控制器:

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

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

View:(to display success message)

查看:(显示成功信息)

@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

You can see in case of success AJAX just reloading the page, I want it to redirect to the page specified in Controller function and display that success message.

您可以看到,如果 AJAX 成功仅重新加载页面,我希望它重定向到 Controller 函数中指定的页面并显示该成功消息。

回答by Justin Origin Broadband

You are returning a HTTP redirect from the response, which doesn't work with AJAX requests. A client such as a browser would be able to intercept and consume the header information which would then reload the page.

您正在从响应中返回 HTTP 重定向,它不适用于 AJAX 请求。客户端(例如浏览器)将能够拦截并使用标头信息,然后重新加载页面。

Instead, for your particular problem, consider:

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

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

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']);
}

Now, the HTTP/200 OKresponse received by your AJAX will execute location.reloadand the flashed session data will be available to the view.

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