簡體   English   中英

如何使用ajax動態地向我的帖子添加評論?

[英]How do I add comments to my post dynamically with ajax?

我正在嘗試通過動態更新評論的 ajax 請求向現有帖子添加評論。 每個帖子都加載了一個“data-post-id”屬性,該屬性保存了來自 Post eloquent 模型的 id。 data-post-id 工作得很好,因為當我通過 chrome 工具檢查 html 元素時,我可以看到它保存了帖子的 id,但是,我不確定如何選擇包含特定 id 的帖子並添加一個新的評論 div 到它。

<div posts>
   <div post data-post-id="">
        <div comments>
            <div comment>
             </div>
        </div>
    </div>
 </div>


  $(document).on("submit","#addComments", function (e){
        e.preventDefault();

        let comment = $("input[name=comment]").val();
        let _token   = $('meta[name="csrf-token"]').attr('content');
        let postID = $(this).attr('data-post-id');

        $.ajax({
            url:"/comments/" + postID,
            method:"POST",
            data:{
                comment:comment,
                _token:_token,
                postID:postID,
            },
            success:function(response){
                addNewComment(response,postID);
                $('#addComments')[0].reset();
                // console.log(response)
            }
        });

    });
function addNewComment(response,postID){
        var $comment = $commentTemplate.clone();
        $comment.find('[data-source="commentBody"]').html(response.comment.body);
        $comment.find('[data-source="commentCreatedTime"]').html(moment().startOf('second').fromNow());
        $('[posts]').find('[post][data-post-id="'+postID+'"]').closest('[comments]').append($comment.html());
       
    }

評論提交到這個網址:

Route::post('/comments/{postID}',[CommentController::class,'store'])->name('addComment');

提交評論的表單也有 data-post-id 屬性,它的內容被每個帖子填滿。

<form id="addComments" class="mb-2" data-post-id="">
      @csrf
      <div class="comment-input">
          <input type="text" 
           name="comment" class="form-control" 
           placeholder="Write a new comment">
       </div>
 </form>

我認為問題來自.closest('[comments]') 最接近返回與作為參數傳遞的選擇器匹配的最接近的父級

在您的情況下[comments][post]的子項,因此請改用它

$('[posts]').find(`[post][data-post-id="${postID}"] > [comments]`).append($comment.html());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM