如何使用Ajax向页面添加评论

时间:2019-05-31 08:47:37

标签: php ajax laravel-blade

我正试图允许用户在文章中发表评论,但是以某种方式,以便不重新加载我的页面,我必须使用ajax,对此我也不了解。这是我的评论部分的样子:

<div class="usrcmmnt_list">
      @foreach($comments as $comment)
      <div class="usrcmmnt flex_box">
        <div class="usrcmmnt_pic">
          <img src="{{ $comment->user['profile_image'] }}">
        </div>
        <div class="usrcmmnt_area">
          <p class="usrcmmnt_name">{{ $comment->user['name'] }}</p>
          <div class="usrcmmnt_box">
            <p class="usrcmmnt_text">{{$comment['content']}}</p>
            <p class="usrcmmnt_time"><img src="{{ url('/img/icon_time.png') }}">{{ date("m/d H:m", strtotime($comment->created_at)) }}</p>
          </div>
        </div>
      </div>
      @endforeach
    </div>
    <div class="comment_write">
      <textarea placeholder="Write a comment" name="comment" id="comment" maxLength="255"></textarea>
      <p class="usrcmmnt_text" id="textarea_warning"></p>
      <span class="alert"></span>
      <button class="btn btn_orange btn_m_2" id="saveComment" type="submit">Post comment</button>
    </div>
</div>

在我的脚本部分中,我有此内容,但它仅复制了现有注释。这只是我的测试:

$('.comment_write button').on('click', function(e){
  e.preventDefault();
  var tmp = document.createElement('div');
  $(tmp).load('myurl', function(data){
    // usrcmmnt_list
    var tmp2 = document.createElement('div');
    $(tmp2).html(data);
    var list = $(tmp2).find('.usrcmmnt_list');

    $(".usrcmmnt_list").append(list);
  });
});

如何使用ajax实现我的目标?

2 个答案:

答案 0 :(得分:1)

有多种方法,其中一种:

  • 您可以将注释循环(@foreach)移到部分视图
  • 创建一个端点以保存用户注释,并将新注释部分返回为html
  • 更新DOM

1。。创建一个新的部分\resources\views\partials\comments.blade.php并将其包含在您的评论部分:

   @if ($comments)
    @foreach($comments as $comment)
          <div class="usrcmmnt flex_box">
            <div class="usrcmmnt_pic">
              <img src="{{ $comment->user['profile_image'] }}">
            </div>
            <div class="usrcmmnt_area">
              <p class="usrcmmnt_name">{{ $comment->user['name'] }}</p>
              <div class="usrcmmnt_box">
                <p class="usrcmmnt_text">{{$comment['content']}}</p>
                <p class="usrcmmnt_time"><img src="{{ url('/img/icon_time.png') }}">{{ date("m/d H:m", strtotime($comment->created_at)) }}</p>
              </div>
            </div>
          </div>
          @endforeach
    @else
    No comments
    @endif

2。。您的评论部分应如下所示:

<div class="usrcmmnt_list">
    <div id="comments-list">
    @include('partials.comments')
    </div>
    <div class="comment_write">
      <form method="post" action="{{ route('save.comment') }}" id="saveCommentForm">
      <textarea placeholder="Write a comment" name="comment" id="comment" maxLength="255"></textarea>
      <p class="usrcmmnt_text" id="textarea_warning"></p>
      <span class="alert"></span>
      <button class="btn btn_orange btn_m_2" id="saveComment" type="submit">Post comment</button>
      </form>
    </div>
</div>

3。。在CommentsController中创建保存评论方法(将用于通过ajax调用保存用户评论):

public function save(Request $request)
{
    /* we assume that your ajax save route is named comment.save */
    /* you might need the postId if you save the comments for a post */
    $comment = $request->input('comment');
    $user    = auth()->user();
    $comment = Comment::create([
        'user_id'=> $user->id,
        'content'=> $comment
    ]);
    $comments = Comment::with('user')->all();
    return view('comments.blade');
}

4。。您的ajax调用:

$(document).ready(function(){
    $('#saveCommentForm').on('submit', function(event) {
        event.preventDefault(); // prevent the form from submiting
        var $form = $(this),
            url = $form.attr('action');

        $.ajax({
            url: url,
            method: 'POST', 
            data: $form.serialize(),
            success: function(response) {
                $('#comments-list').html(response); //update the dom
            },
            error: function() {
                alert('An error occurred. Please try again later.');
            }
        });
    });
});

我希望这会帮助您入门。

答案 1 :(得分:0)

您必须尝试这样的事情。

$(document).on('click', '#saveComment', function(){
    if($('#comment').val()==''){
        alert('Please write a Comment First!');
    }
    else{
        var comment = $('#comment').val();
        $.ajax({
            type: 'POST',
            url: '<your url goes here>',
            data: {"comment": comment},
            success: function(){
               // update comment listing.
            },
        });
    }

});

不过,这里是您可以遵循的完整教程。 https://www.sourcecodester.com/tutorials/php/11819/laravel-comment-post-using-ajax.html