【问题标题】:How do i update comment count using Ajax如何使用 Ajax 更新评论计数
【发布时间】:2020-05-12 11:46:20
【问题描述】:

我正在 Django 中开发一个项目,用户可以在其中评论帖子。当用户对帖子的评论将计数增加到 1 时,我如何更新每个帖子的评论计数。我尝试将 id 添加到 div 但没有任何反应。我该如何实现?

主页模板:

<!-- Comment count post is an object of all post in homepage -->
<div class="col-4 col-md-4 col-lg-4" id="newfeeds-form">
<a href="{% url 'site:comments' post.id %}" class="home-comment-icon z-depth-0">
<img src="{{ '/static/' }}images/comment.png" width="19" height="19" alt="comment-icon">
{% if post.comments.all|length > 999 %}
<span class="font-weight-bold dark-grey-text" id="number-of-comments">
{{ post.comments.count|floatformat }}
</span>
{% else %}
<span class="font-weight-bold dark-grey-text" id="number-of-comments">
{{ post.comments.count }} Comment{{ post.comments.count|pluralize }}
</span>
{% endif %}
</a>
</div>

<!-- New Feeds Comment Form -->
<div id="newfeeds-form">
{% include 'ajax_newfeeds_comments.html' %} 
</div>

Ajax 提交评论:

$(document).ready(function() {

$('.feeds-form').on('submit', onSubmitFeedsForm);
$('.feeds-form .textinput').on({
'keyup': onKeyUpTextInput,
'change': onKeyUpTextInput // if another jquery code changes the value of the input
});

function onKeyUpTextInput(event) {
var textInput = $(event.target);
textInput.parent().find('.submit').attr('disabled', textInput.val() == '');
}

function onSubmitFeedsForm(event) {
event.preventDefault();

// if you need to use elements more than once try to keep it in variables
var form = $(event.target);
var textInput = form.find('.textinput');
var hiddenField = form.find('input[name="post_comment"]');

$.ajax({
  type: 'POST',
  url: "{% url 'site:home' %}",
  // use the variable of the "form" here
  data: form.serialize(),
  dataType: 'json',
  beforeSend: function() {
    // beforeSend will be executed before the request is sent
    form.find('.submit').attr('disabled', true);
  },
  success: function(response) {
    // as a hint: since you get a json formatted response you should better us "response.form" instead of response['form']
    $('#newfeeds-form' + hiddenField.val()).html(response.form);
    // do you really want to reset all textarea on the whole page? $('textarea').val('');
    textInput.val(''); // this will trigger the "change" event automatically
  },
  error: function(rs, e) {
    console.log(rs.resopnseText);
  },
  complete: function() {
    // this will be executed after "success" and "error"
    // depending on what you want to do, you can use this in the "error" function instead of here
    // because the "success" function will trigger the "change" event automatically
    textInput.trigger('change');
  }
});
}

});

【问题讨论】:

    标签: python jquery django


    【解决方案1】:

    如果您确定每次请求都会创建一条新评论,那么您可以通过增加所需 html 元素的计数来实现。

    到目前为止,我还没有使用过 python 或 django,但尝试过优化代码。

    <!-- ... -->
    <div class="col-4 col-md-4 col-lg-4" id="newfeeds-form">
        <span class="font-weight-bold dark-grey-text" id="number-of-comments" data-number="{{ post.comments.count }}">
          {% if post.comments.count > 999 %}
            {{ post.comments.count|div:1000|floatformat:1 }}k Comments
          {% else %}
            {{ post.comments.count }} Comment{{ post.comments.count|pluralize }}
          {% endif %}
        </span>
    </div>
    <!-- ... -->
    
    function onSubmitFeedsForm(event) {
      // ...
      $.ajax({
        // ...
        success: function(response) {
          $('#newfeeds-form' + hiddenField.val()).html(response.form);
          textInput.val('');
    
          // how you can increment the value of the amount of comments
          refreshNumberOfComments();
        },
        // ...
      });
      // ...
    }
    // ...
    
    function refreshNumberOfComments() {
      var numberOfCommentsElement = $('#number-of-comments');
      var numberOfComments = parseInt(numberOfCommentsElement.data('number')) + 1;
    
      numberOfCommentsElement.data('number', numberOfComments);
    
      if (numberOfComments == 1) {
        numberOfCommentsElement.text(numberOfComments + ' Comment');
      } else if (numberOfComments > 999) {
        numberOfCommentsElement.text((numberOfComments / 1000).toFixed(1) + 'k Comments');
      } else {
        numberOfCommentsElement.text(numberOfComments + ' Comments');
      }
    }
    

    另一种选择是向请求提供有关 cmets 数量的信息。 所以你可以像这个例子一样在jQuery中制作它

    $.ajax({
      // ...
      success: function(response) {]
        $('#newfeeds-form' + hiddenField.val()).html(response.form);
        textInput.val('');
    
        // your server side script should implement a new field "number_of_comments"
        refreshNumberOfComments(response.number_of_comments); // for this call the function above has to get a parameter
      },
      // ...
    });
    

    【讨论】:

    • @UfguFugullu...您的代码起初可以工作,但添加 else 语句的注释计数不再增加。请看我刚刚更新的问题。
    • 有没有办法做到这一点? 1comment, 2cmets, 如果超过 999 则显示 1k
    • 我注意到您的代码中有错误。如果没有评论,当我提交第一个评论时计数不会增加,除非我手动重新加载页面然后我得到 1,当我提交另一条评论时它自动增加到 2。我一直在尝试自己解决这个问题,它更复杂.
    • 计数只增加第一个帖子,当我在第二个帖子中提交评论时,计数不会增加,直到我手动重新加载我的页面。
    • @MrHize 我已经编辑了我的答案,希望能回答你的问题
    猜你喜欢
    • 2013-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-29
    • 1970-01-01
    相关资源
    最近更新 更多