【问题标题】:django ajax multiple form submissiondjango ajax 多表单提交
【发布时间】:2015-12-21 22:16:35
【问题描述】:

我的模板看起来像:

    {% 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 %}

这里我有评论回复。 我的 cmets 和评论回复正确列出。 这里我想要的是当我点击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 时,它会显示所有的评论回复表单,但我只想在我点击的地方显示表单

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

我该如何解决这个问题?

【问题讨论】:

    标签: javascript jquery ajax django forms


    【解决方案1】:

    它显示所有这些是因为您要求显示所有具有“comment-replyform”类的元素,而不是您必须专注于单击元素内的元素。 为此,请替换:

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

    作者:

    $(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. 最后用$(this).prev('.comment-reply').val('');替换$('#id_comment_reply').val('');,它应该可以工作

    【讨论】:

    • 当我做 $(this).children(".comment-replyform").show();什么都没有显示
    • 对不起,那时还不是孩子,这个应该可以解决问题:$(this).nextAll(".comment-replyform").show();
    • 我也这样做了。当我单击第一个单击时,它会显示两个表单,当我单击第二个单击时,它仅显示第二个表单,但未显示单击表单。有什么帮助吗?
    • $(this).next().next().show();如果您的 html 代码正是您提供的那个,这个应该可以工作(第一个是
      第二个是您需要的)
    • 我不应该在这里提供.comment-replyform" ??
    猜你喜欢
    • 1970-01-01
    • 2019-01-08
    • 2020-11-24
    • 2016-08-20
    • 2017-07-26
    • 2017-12-16
    • 2021-03-19
    • 2018-07-21
    • 2019-03-24
    相关资源
    最近更新 更多