如何使用ajax添加评论,而无需刷新即可在laravel中查看新评论

时间:2019-04-19 16:14:27

标签: php ajax laravel

我已成功向数据库添加了新注释,但是为什么必须刷新页面才能看到新注释。我对这个问题感到困惑。我的代码的哪一部分错了?

这是我的代码。

路线

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

评论控制器 注意:我使用哈希对帖子ID进行解码。

public function store(Requests\CommentStoreRequest $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>

1 个答案:

答案 0 :(得分:0)

重定向为:

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"]);