【问题标题】:How to load specific div or id ajax and laravel如何加载特定的 div 或 id ajax 和 laravel
【发布时间】:2017-06-06 22:03:52
【问题描述】:

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

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

最后是我编辑评论的模态:

<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') ;通过这一行,我成功加载了已编辑的评论,但是,它加载了已编辑评论上的所有 cmets,因此我必须刷新整个页面以仅显示已编辑的评论。

【问题讨论】:

  • 你有来自模态的评论;您是否有理由不能使用模态中包含的数据?是相同的数据,不是吗?
  • @Daedalus 就像这样工作,模态包含评论 id,然后我编辑评论,一旦编辑,评论应该通过模态传递到 id="display-comment"。所以理论上模态中的数据应该替换旧的 id="display-comment" 数据.. 或者至少这就是我正在寻找的。​​span>
  • 那么,你为什么不能这样做呢? $(divcomment).find('#display-comment').text(comment),作为 ajax 的 done 函数的最后一行。
  • 另外,请停止对非sn-p代码使用sn-p功能。如果您只有要缩进的代码,请使用花括号按钮:{},而不是用于演示可运行 javascript、css 或 html 代码的 sn-p 按钮。请参阅here 了解更多信息。
  • @Daedalus 对 sn-p 功能感到抱歉,我是新手。关于代码,同样的,我需要手动重新加载页面才能看到编辑的评论

标签: javascript php ajax laravel


【解决方案1】:

假设发送到 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 */
});

【讨论】:

  • 不会自动加载评论...我不知道还能做什么@Daedalus
  • @JuanRincón 没有任何错误,或者对问题的更好描述,我也不知道。
  • 没有错误。这是 chrome 控制台给我的:{new_comment: "Primer Comentario editado...", success: true} new_comment : "Primer Comentario editado..." success : true 和表单数据:comment:Primer Comentario editado... commentId:1 _token:6llgVyfmAstqHEuVpnrXpS4hg0u8yRHfnaoD9ff5 _method:PUT dataType:json
  • @JuanRincón 请显示控制台的屏幕截图;否则不清楚如何在 json 中获取两个对象。
  • [link](imgur.com/haLgEbJ"><imgsrc="i.imgur.com/haLgEbJ.png" title="source: imgur.com" />) [link2](imgur.com/fU4bINb"><imgsrc="i.imgur.com/fU4bINb.png" title="来源: imgur.com" />) [link3](imgur.com/OnU6kFL"><imgsrc="i.imgur.com/OnU6kFL.png" title="来源:imgur.com" />) @Daedalus
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-10
  • 2016-04-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多