【问题标题】:Laravel session flash message appears multiple times on pagebackLaravel session flash 消息在 pageback 上多次出现
【发布时间】:2017-02-04 16:22:00
【问题描述】:

在我的控制器中:

 Session::flash('created', "Student created");
 return Redirect::to('student');

在我看来:

 @if(Session::has('created'))
 alert('updated');
 @endif

【问题讨论】:

  • 你的问题到底是什么?
  • 你为什么使用会话?您可以使用 Redirect::route() 方法作为更好的解决方案。

标签: javascript php laravel laravel-5.2 session-state


【解决方案1】:

显示会话消息

@if(Session::has('success'))
  <div class="alert alert-success alert-dismissable alert-box">
    <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
    {{ Session::get('success') }}               
  </div>
@endif
@if(Session::has('error'))
  <div class="alert alert-danger alert-dismissable alert-box">
    <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
    {{ Session::get('error') }} 
  </div>
@endif  

从控制器调用

return redirect()->back()->with('success', 'Data added successfully');

【讨论】:

  • 当我在浏览器中按来回按钮时多次显示警报
【解决方案2】:

请避免不必要地使用会话。您可以使用Redirect::route。检查以下示例:

1) 将$strChecked = false; 初始化到你的学生路由控制器,然后将$strChecked = true; 设置到你的学生更新方法中。

2) 用return \Redirect::route('student')-&gt;with('strChecked', $strChecked);替换您的退货行

3) 那么在你看来,你可以使用:

@if($strChecked)
    alert('updated');
@endif

编辑:

让我用我的工作演示代码来说明:

1) 路线:

Route::get('flash', 'FlashController@flashIndex')->name('frontend.flash');
Route::post('flash/update', 'FlashController@studentUpdate')->name('frontend.flash.update');

2) 查看:

@section('content')
{{ Form::open(['route' => 'frontend.flash.update', 'class' => 'form-horizontal']) }}

{{ Form::submit('Demo', ['class' => 'btn btn-primary', 'style' => 'margin-right:15px']) }}  

{{ Form::close() }}

@endsection
@section('after-scripts-end')
    <script>
        @if(Session::has('created'))
         alert('updated');
        @endif
    </script>
@stop

3) 控制器:

//Method to display action...
public function flashIndex()
{
 return view('frontend.flash');  
}

//Method to update action...
public function studentUpdate()
{
 Session::flash('created', "Student created");
 return Redirect::to('flash'); 
}

希望这能消除您的疑虑。

上面的例子在我的最后工作正常。如果这不适合您,请描述您的代码。

【讨论】:

  • 抱歉,无法正常工作,无法在视图中获取 $strChecked 值。
  • 请说明您在使用此代码时遇到的错误?
  • $strChecked 值未定义,因为它写在 jquery 或用户在页面中的任何位置显示未定义
  • 明白了,可能是您没有专注于第 1 点)。您需要将 $strChecked 传递给初始视图时间(即初始化此视图的方法)。详细更新您的问题,以便我们解决。
  • 对不起,它仍然不适合我是不是有任何其他的方式来闪光警报?并且代码和上面一样我无法获得@if($strChecked) alert('updated'); @endif 显示 $strChecked 未定义。
【解决方案3】:

对我来说,我没有使用Session::get('key'),而是使用Session::pull('key'),它只会弹出一次。

例如

@if(Session::has('success'))
    {{ Session::pull('success') }} 
@endif  

根据Laravel 7.x doc

pull 方法将在单个语句中从会话中检索和删除项目:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-09
    • 1970-01-01
    • 2017-10-14
    • 2021-05-28
    • 1970-01-01
    • 2019-03-04
    相关资源
    最近更新 更多