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
            }
        });
    }
    
    评论

报告相同问题?