【发布时间】:2021-10-04 23:16:00
【问题描述】:
我正在尝试通过动态更新 cmets 的 ajax 请求将 cmets 添加到现有帖子中。每个帖子都加载了一个“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());
}
评论提交到这个url:
Route::post('/comments/{postID}',[CommentController::class,'store'])->name('addComment');
提交 cmets 的表单也有 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>
【问题讨论】:
-
你有多个这样的表格?
-
我在同一页面中有另一个表单用于提交帖子。为什么?
-
该表单的 ID 是否相同?你试过打印 postID 了吗?
-
每个表单都有一个唯一的 ID。是的。当我检查我的 html 或记录它时,我得到了正确的 postID。
标签: javascript html jquery css laravel