如何加载特定的div或id ajax和laravel

时间:2017-06-06 22:03:52

标签: javascript php ajax laravel

我在laravel的应用程序上有一个评论系统,我可以用ajax编辑我的评论但是一旦编辑它就不会自动加载编辑的评论。要查看已编辑的评论,我需要手动重新加载页面。我会在这里放一些代码。

这是JS:

    jbRemoveRow.addActionListener(new ActionListener() {
      @Override public void actionPerformed(ActionEvent e) {
        JTable table = (JTable)SwingUtilities.getAncestorOfClass(
            JTable.class, (Component) e.getSource());
        int row = table.getEditingRow();
        table.getCellEditor().stopCellEditing();
        ((PSRBTableModel)table.getModel()).removeRow(row);
        // table.updateUI();
      }
    });

这是Html:

        var commentId = 0;
        var divcomment = null;

        $('.edit-comment').click(function(event){
          event.preventDefault();
          /* Accedemos al Div Que contiene el Panel*/
          var divcomment = this.parentNode.parentNode;
          /* Buscamos el Contenido con Id display-text  */
          commentId = $("#comment-post", event.target.parentNode.parentNode).data('commentid');
          var commentBody = $(divcomment).find('#display-comment').text();
          $('#comment').val(commentBody);
          $('#edit-comment').modal();
           /* Asignas a tu modal */
        });

        $('#modal-save').on('click', function(){
            $.ajax({
                method: 'PUT',
                url: urlEdit,
                data: {
                    comment: $('#comment').val(),
                    commentId: commentId,
                    _token: token,
                    _method: 'PUT',
                    dataType: 'json',
                 }
            })
            .done(function (msg){
                $(divcomment).text(msg['new_comment']);
                $('#edit-comment').modal('hide');
            });
        });

在视图上创建了2个变量

 <article class="row">
                            <div class="col-md-3 col-sm-3 hidden-xs">
                              <figure class="thumbnail">
                                <img class="img-responsive" src="/uploads/avatars/{{ $comment->user->profilepic  }}" />
                                <figcaption class="text-center">{{ $comment->user->name }}</figcaption>
                              </figure>
                            </div>
                            <div class="col-md-8 col-sm-8">
                              <div class="panel panel-default arrow left">
                                <div class="panel-body">
                                  <header class="text-left">
                                    <div class="comment-user"><i class="fa fa-user"></i> {{ $comment->user->name }}</div>
                                    <time class="comment-date" datetime="{{ $comment->created_at->diffForHumans() }}"><i class="fa fa-clock-o"></i> {{ $comment->created_at->diffForHumans() }}</time>
                                  </header>
                                  <div id="comment-post" data-commentid="{{ $comment->id }}">
                                      <p id="display-comment">{{ $comment->comment }}</p>
                                  </div>
                                </div>

                                <div class="panel-footer list-inline comment-footer">
                                  @if(Auth::guest())

                                  No puedes responder ningún comentario si no has ingresado.

                                  @else

                                  @if(Auth::user() == $comment->user)
                                    <a href="#" data-toggle="modal" data-target="edit-comment" class="edit-comment">Editar</a> <a href="#" data-toggle="modal" data-target="delete-comment" class="delete-comment">Eliminar</a>
                                  @endif

                                  @if(Auth::user() != $comment->user)
                                    <a href="#">Responder</a>        
                                  @endif

                                  @endif
                                </div>

                              </div>
                            </div>
                          </article>

最后我编辑评论的模态:

  var token = '{{ Session::token() }}';
  var urlEdit = '{{ url('comments/update') }}';

一切正常,但我唯一需要的是加载已编辑的评论而不刷新整个页面,顺便说一句,我使用了$(&#39;#display-comment&#39;)。load(document。网址+&#39; #display-comment&#39;);并且使用这一行我成功加载了已编辑的注释,但是它会加载所编辑的注释,所以我必须刷新整个页面才能显示已编辑的注释。

1 个答案:

答案 0 :(得分:0)

假设发送到php端的数据与您想要更新的数据相同,则以下内容应该有效:

$('#modal-save').on('click', function(){
    var comment = $('#comment').val();
    // shove the edited comment into a variable local to the modal handler
    $.ajax({
        method: 'PUT',
        url: urlEdit,
        data: {
            comment: comment, // reference said variable for ajax data
            commentId: commentId,
            _token: token,
            _method: 'PUT'
         },
         dataType: 'json'
    })
    .done(function (msg){
        //$(divcomment).text(msg['new_comment']);
        // I commented out the above line as it clears the
        // divcomment div's text entirely.
        // Comment out the below 'if check' if it is not needed.
        if (msg.success === true) {
            $(divcomment).find('#display-comment').text(comment);
            // And overwrite the #display-comment div with the new
            // data if the user was successful in editing the comment
        }
        $('#edit-comment').modal('hide');
    });
});

previous question of yours中,你在处理ajax的东西的php端有一个控制器方法。而不是重定向(因为它是ajax,没有重定向),你应该返回json来指示动作是否成功。这是一个例子:

public function update(Request $request)
{

    //...

    $comment = Comment::find($request['commentId']);
    if (Auth::user() != $comment->user) {
        return response()->json(['success' => false], 200);
    }

    //...

    return response()->json(['new_comment' => $comment->comment, 'success' => true], 200);
}

我在javascript方面的答案中引用了上面的json;如果您不打算使用json响应,那么只需注释掉该行(正如我在代码中所述)。

<强>更新: 我错过了你早期的代码块;你在编辑链接的处理程序之外声明divcomment,然后再次在该处理程序内重新声明它。我在之前的回答中错过了这个,所以只需从中删除var,所以它使用外部声明,修复你的代码:

var commentId = 0;
var divcomment = null; //this is already declared, no reason to declare it
// again

$('.edit-comment').click(function(event){
    event.preventDefault();
    /* Accedemos al Div Que contiene el Panel*/
    divcomment = this.parentNode.parentNode;
 // ^ remove the var, making this use the global variable you already
 // made above
    /* Buscamos el Contenido con Id display-text  */
    commentId = $("#comment-post", event.target.parentNode.parentNode).data('commentid');
    var commentBody = $(divcomment).find('#display-comment').text();
    $('#comment').val(commentBody);
    $('#edit-comment').modal();
    /* Asignas a tu modal */
});