django ajax多表格提交

时间:2015-09-24 10:35:12

标签: javascript jquery ajax django forms

我的模板如下:

    {% for comment in service.comments.all %}
    {{comment.comment}} -- commented by {{comment.user}}<br/>

  <div id="comment-reply">
        `{% for reply in comment.comment_replies.all %}`

    <p>{{reply.comment_reply}} -- replied by {{reply.user}}</p><br/>

    {% endfor %}
  </div>


    <a class="myClick" href="#">Reply</a><br/>
    <form class="comment-replyform" action="some_url" method="post" style="display: none;">{% csrf_token %}

      {{ comment_reply_form.as_p }}

    <input type="submit" name="submit" value="Reply">
    </form>

    {% empty %}
    No comments 
    {% endfor %}

我在这里发表评论意见回复。     我的评论和评论回复正确列出。     这里我想要的是当我点击Click时我想显示评论回复表格,显示正常...

我的jquery看起来像:

    $(".myClick").click(function(event){
  event.preventDefault();
  $(".comment-replyform").show();
  $(".myClick").hide();
 })

    $('.comment-replyform').on('submit', function(event){
            event.preventDefault();
      $.ajax({
               url: $(this).attr('action'),
               type: $(this).attr('method'),
               data: $(this).serialize(),
               success: function(response) {
                    $('#id_comment_reply').val('');
                    $('#comment-reply').append("<p>"+response.comment_reply+" -- "+"replied by "+ response.user+"</p><br/>")
                }

                });        
    })

问题是,当我点击Click时,它会显示评论回复的所有表单,但我只想在我点击的地方显示表单

另一件事是当我提交第一张表格时效果很好,但是当我提交第二张或第三张表格时...值会显示在第一个表格上。我的意思是第二个表格的评论回复附加到第一个。

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

它显示了所有这些因为你问了所有的元素&#34; comment-replyform&#34;要显示,你必须专注于被点击元素内的一个。 为此,请替换:

 $(".comment-replyform").show();

by:

$(this).next().next(".comment-replyform").show();;

对于你问题的第二部分,这是因为你应该只有一个具有特定ID的元素,所以:

  1. 在for循环中将id="comment-reply"替换为class="comment-reply"

  2. $('#comment-reply').append(...)替换为$(this).prev('.comment-reply').append(...)

  3. 最后将$('#id_comment_reply').val('');替换为$(this).prev('.comment-reply').val('');,它应该可以正常工作