duan19911992 2016-09-15 13:53
浏览 24

在Laravel 5中闪烁反馈消息

I want to flash feedback messages like "An entry has been created successfully" or "You don't have enough permissions to access this item".

I want to avoid embedding these messages straight into views, because they can re-appear, for example, when a user navigates back to the previous page with his browser.

To solve this problem, I have a javascript function that acts like following:

(showFlashMessage(){
    // 1. make an ajax request
    // 2. retrieve a flash message (if any)
    // 3. display the message
})();

This way, the problem of the reappearance of the flash messages is solved. However, by the time the request is made, the flash message has already disappeared. How should I solve this problem?

  • 写回答

2条回答 默认 最新

  • dongzanghua8422 2016-09-15 20:51
    关注

    If you want to solve the problem on the server side you can make use of the Session facade like so:

    In your controller:

    function create() {
        if(Gate::allows('createAccess')) {
            Session::flash('error', 'You don't have enough permissions to access this item!');
    
            return redirect()->back();
        }
    
        // Create the model or perform any other logic
    
        Session::flash('success', 'An entity has been created successfully!');
    
        return view('entities.show');
    }
    

    Then you can have a partial named message.blade.php which is included in your entities.show view:

    @if (Session::has('message'))
        <div class="alert alert-info">
            <p>{{ Session::get('message') }}</p>
        </div>
    @endif
    

    If you want to solve the problem on the client side you can call your message function (for example sweet alert message) in the success callback when the request has been completed successfully:

    function showMessage() {
        $.ajax({
            url: 'your-url',
            data: {
                // Your data here
            },
            success: function() {
                // Show success message
            },
            error: function() {
                // Show error message
            }
        });
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 2024-五一综合模拟赛
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭