繁体   English   中英

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

[英]How to add a comment to a page using ajax

我试图允许用户以某种方式在文章中发表评论,以便不重新加载我的页面,我必须使用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实现我的目标?

有多种解决方法,其中一种:

  • 您可以将注释循环(@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.');
            }
        });
    });
});

希望这会帮助您入门。

您必须尝试这样的事情。

$(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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM