如何加载特定的div或id ajax和laravel [英] How to load specific div or id ajax and laravel

查看:71
本文介绍了如何加载特定的div或id ajax和laravel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在laravel中的应用程序上有一个评论系统,我可以使用Ajax编辑我的评论,但是一旦编辑,它不会自动加载已编辑的评论.要查看编​​辑后的评论,我需要手动重新加载页面.我将在此处放置一些代码.

i have a comment system on my app in laravel and i can edit my comments with ajax but once edited it doesn't load automatically the edited comment. To see the edited comment i need to reload the page manually. I will put some of the code here.

这是JS:

        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');
            });
        });

这是HTML:

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

在视图上创建2个变量

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

最后是编辑评论的模式:

and finally the modal where i edit the comment:

<div class="modal fade" id="edit-comment" tabindex="-1" role="dialog">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" style="color:#000;">Editar Comentario</h4>
      </div>
      <div class="modal-body">
        <form>
          <div class="form-group">
            <label for="comment">Editar comentario</label>
            <textarea class="form-control" name="comment" id="comment"></textarea>
          </div>
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn-comment-dismiss btn-comment-modal" data-dismiss="modal"><span class="glyphicon glyphicon-remove"></span> Cerrar</button>
        <button type="button" class="btn-comment-edit btn-comment-modal" id="modal-save"><span class="glyphicon glyphicon-ok"></span> Editar</button>
      </div>
    </div>
  </div>
</div>

一切正常,但我唯一需要做的是重新加载已编辑的注释,而不刷新整个页面,但我使用了$('#display-comment').load(document.URL +'#display-comment') ;在这一行中,我成功加载了已编辑的注释,但是,它已将所有注释加载到了已编辑的注释中,因此我必须刷新整个页面以仅显示已编辑的注释.

Everything's working but the only thing i need is to load the edited comment back without refresh the whole page, btw i used $('#display-comment').load(document.URL + ' #display-comment'); and with this line i succesfully load the edited comment but, it load all the comments on the edited one, so i have to refresh the whole page to show just the edited.

推荐答案

假设发送到php端的数据与您要更新的数据相同,则以下方法应该起作用:

Assuming that the data sent to the php side of things is the same data that you then want to update to, the following should work:

$('#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');
    });
});

您之前的问题中,您有php端处理ajax的控制器方法.而不是重定向(因为它是ajax,所以没有重定向),而应该返回json来指示操作是否成功.这是一个示例:

In a previous question of yours, you had a controller method on the php side of things that handled the ajax. Instead of redirecting(since it is ajax, there is no redirect), you should instead return json to indicate whether the action was successful or not. Here is an example of that:

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响应,则只需注释掉该行即可(正如我在代码中也提到的那样).

I referenced the above json in my answer on the javascript side of things; if you are not going to use the json response, then simply comment out the line(as I also noted in the code).

更新: 我错过了您先前的代码块中的某些内容;您在编辑链接的处理程序外部声明了divcomment,然后又在该处理程序内部重新声明了它.我在较早的答案中错过了这一点,因此只需从中删除var,以便它使用外部声明来修复您的代码:

Update: I missed something in your earlier block of code; you declare divcomment outside of the edit link's handler, but then you re-declare it inside of that handler again. I missed this in my earlier answer, so simply deleting the var from it, so it uses the outside declaration, fixes your code:

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 */
});

这篇关于如何加载特定的div或id ajax和laravel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆