Ajax Post不适用于Django中循环中的每个请求

时间:2018-10-13 22:05:32

标签: python jquery ajax django

我有一个博客页面。博客具有“评论”和评论具有“回复”作为相关对象。创建对博客的评论并创建对评论的回复(使用ajax调用)。创建评论到博客工作正常。但是创建对评论的回复仅适用于第一个评论。我知道html在ajax帖子中应该有唯一的id,所以如果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); 
        }
    });
};

});

0 个答案:

没有答案