如何使用 Ajax 添加注释,而无需刷新以查看 Laravel 中的新注释



我已成功将新注释添加到数据库,但为什么它必须刷新页面才能看到新注释。 我对这个问题感到困惑。 我的代码哪里有问题?

这是我的代码。

路线

Route::post('blog/{post}/comments/store', 'AuthMemberCommentController@store')->name('comment.add');

注释控制器注意:我使用哈希在帖子ID上使用解码。

public function store(RequestsCommentStoreRequest $request)
{
    if($request->ajax()){
        $comment       = new Comment;
        $comment->body = $request->get('comment_body');
        $comment->user()->associate($request->user('member'));
        $key    = $request->get('post_id');
        $result = Hashids::connection('main')->decode($key)[0];
        $post   = Post::find($result);
        $post->comments()->save($comment);
        $response = array(
            'status' => 'success',
            'msg' => 'comment has been added',
        );
        return Response::json($response);
    }

}

表单注释

{!! Form::open(array(
                            'route'  => ['comment.add', $post->slug],
                            'method' => 'POST',
                            'id'     => 'form',
                            'name'   => 'form',
                            'data-parsley-validate'))
                        !!}

                            <div class="form-group {{ $errors->has('comment_body') ? 'has-error': '' }}">
                                {!! Form::textarea('comment_body', null, array(
                                    'class'       => 'form-control elastic',
                                    'id'          => 'comment_body',
                                    'rows'        => '3',
                                    'name'        => 'comment_body',
                                    'placeholder' => 'Write Something...',
                                    'required', 'minlength="4"')
                                    )
                                !!}
                                @if($errors->has('comment_body'))
                                    <span class="help-block">{{$errors->first('comment_body')}}</span>
                                @endif

                                <input type="hidden" name="post_id" value="{{ $parameter }}" />
                            </div>
                            <div class="form-group">
                                {!! Form::submit('Submit', array(
                                    'name'    => 'submit',
                                    'class'   => 'btn btn-primary',
                                    'id'      => 'btnComments'
                                    )) !!}
                            </div>
                        {!! Form::close() !!}
ajax

,所以这是我的ajax将新注释存储到数据库中

<script>
$(document).ready(function(){
    var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
    $('#form').on('submit', function(event) {
        event.preventDefault();
        var form = $(this);
        var url = form.attr('action');
        $.ajaxSetup({
            headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }
        });
        $.ajax({
            // url: '{{route('comment.add',[$post->slug])}}',
            url: url,
            type: 'POST',
            data: form.serialize(),
            dataType: 'JSON',
            success: function (data) {
                console.log(data);
            },
            error: function(data){
                console.log(data);
            }
        });
    });
});
</script>

您重定向为 :

return redirect()->to(app('url')->previous(). '#comments')->with('message-post', 'Comment has been added');

尝试将 JSON 返回为:

return response()->json(["success"=>"true", "message"=>"Comment has been added"]);

最新更新