У меня есть страница блога.Блог имеет «комментарии», а комментарии имеют «ответы» как связанные объекты. Создание комментария к блогу и создание ответа на комментарий при работе с вызовом ajax.Создание комментария к блогу работает нормально.Но создание ответа на комментарий работает только первым комментарием.Я знаю, что HTML должен иметь уникальный идентификатор в посте AJAX, поэтому я использовал класс в форме вместо ID.Публикация ответа на первый комментарий прошла успешно.Но разместив ответ для второго комментария, он разместил для первого комментария.Как управлять вызовом ajax в циклическом запросе?Вот мой код:
Код HTML:
<div class="collapse" id="comment-own">
<div id="ajax">
{% for comment in comments %}
<div class="comment-content">
{ comment.content }}
</div>
<div class="comment-reply">
<div id="rep-ajax">
{% for child_comment in comment.children %}
<div class="comment-content">
{{ child_comment.content }}
</div>
{% endfor %}
</div>
<form method="POST" class="new_reply"> {% csrf_token %}
<input type="text" name="content" id="rep-id" class="form-control" placeholder='Write a reply...'/>
<input type="hidden" name="content_type" value="post" id="id_content_type" />
<input type="hidden" name="object_id" value={{instance.id}} id="id_object_id" />
<input type="hidden" name="parent_id" value="{{comment.id}}" id="id_parent_id">
<input id="submittt" type="submit" value="Reply"/>
</form>
</div>
{% endfor %}
</div>
<form method="POST" class="new_comment"> {% csrf_token %}
<div id="write-comment">
<input type="text" name="content" id="id-content" class="form-control" placeholder='Write a comment...'/>
<input type="hidden" name="content_type" value="post" id="id_content_type" />
<input type="hidden" name="object_id" value={{instance.id}} id="id_object_id" />
<input id="submitt" type="submit" value="Comment"/>
</div>
</form>
Код Ajax:
$(function() {
// Submit post on submit
$('.new_reply').on('submit', function(event){
event.preventDefault();
console.log("form submitted!"); // sanity check
create_reply();
});
// AJAX for posting
function create_reply() {
console.log("create reply is working!"); // sanity check
$.ajax({
url : 'new_comment/', // the endpoint
type : "POST", // http method
data :{ // data sent with the post request
content: $('#rep-id').val(),
content_type : $('#id_content_type').val(),
object_id : $('#id_object_id').val(),
parent_id : $('#id_parent_id').val()
},
// handle a successful response
success : function(json) {
$('#rep-id').val(''); // remove the value from the input
console.log(json); // log the returned json to the console
},
// handle a non-successful response
error : function(xhr,errmsg,err) {
console.log(xhr.status + ": " + xhr.responseText);
}
});
};
});