2016-06-09 68 views
1

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

回答

4

您正在返回来自响应的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

+0

你是否总是必须返回响应才能将数据放入会话中?因为我只写了这段代码'$ request-> session() - > flash('message-type','success');'并且它不工作。为什么? – shigg