Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.4k views
in Technique[技术] by (71.8m points)

javascript - Displaying comments using Ajax

i am working on a project using Django. There are lists of users posts in homepage and each post has a comment form. I was able to implement comment properly on views, but the issue now is when I submit a comment it display empty string instead of the comment, the comment display in chrome console. How do i display comment on each post by user when a form is submitted. I attached an image to my questioin to clarify my question.

enter image description here

home.html

  <div id="newfeeds-form">
  {% include 'ajax_newfeeds_comments.html' %} 
  </div>

ajax_newfeeds_comments.html

<!-- New Feeds comment Text -->
  {% for post in all_images %}
<div class="container newfeeds-comment" id="display-comment">
{% for comment in post.comments_set %}
<div class="row">
<div class="col-1 col-md-1 col-lg-1">
{% if comment.user.profile.profile_pic %}
<img src="{{ comment.user.profile.profile_pic.url }}" class="d-flex rounded-circle" alt="image" height="28" width="28">
{% endif %}
</div>
<div class="col-10 col-md-10 col-lg-10 p-2 ml-1" id="user-commentpost">
<span class="comment-post truncate">
<span class="name text-lowercase">{{ comment.user }}</span>
{{ comment.comment_post }}</span>
</div>
</div>
{% endfor %}
</div>
    {% endfor %} 

  <span class="md-form">
  <form enctype="multipart/form-data" class="feeds-form form-inline md-form form-sm" method="POST" action="{% url 'site:home' %}" id="newfeeds-form{{ post.id }}">
   {% csrf_token %}
  <input type="hidden" value={{post.id}} name="post_comment">
  <img src="{{ request.user.profile.profile_pic.url }}" class="rounded-circle avatar-img" height="28" width="28">
  <textarea name="comment_post" class="textinput textInput animated fadeIn" placeholder="Add a comment..." required="" id="id_comment_post{{ post.id }}" onkeyup=""></textarea>

  <button type="submit" class="submit" id="submit1-{{post.id}}"><i class="fas fa-paper-plane"></i></button>
  </form
  </span>

Views:

  def home_view(request):
#All posts in new feed
all_images = Post.objects.filter(
    Q(poster_profile=request.user, active=True)|
    Q(poster_profile__from_user__to_user=request.user, active=True)|
    Q(poster_profile__to_user__from_user=request.user, active=True)|
    Q(poster_profile__profile__friends__user=request.user, active=True)).distinct().exclude(
    Q(hide_post=request.user, active=True)|
    Q(poster_profile__profile__blocked_users__user=request.user, active=True))

#Comment form homepage
if request.method == 'POST':
    post_id = request.POST.get("post_comment")
    post_obj = Post.objects.get(pk=post_id)
    form = CommentForm(request.POST)
    if form.is_valid():
        comment = form.save(commit=False)
        comment.user = request.user
        comment.commented_image = post_obj
        comment.save()
        # messages.info(request,'You submitted a comment')
        #return redirect('/')
else:
    form = CommentForm()

context = {
    'form': form,
    'all_images': all_images,
}
if request.is_ajax():
    html = render_to_string('ajax_newfeeds_comments.html', context, request=request)
    return JsonResponse({'form': html})

return render(request,'home.html', context)

Ajax:

<script type="text/javascript">
//HomeFeeds Comment
$(document).ready(function() {

$('.feeds-form').on('submit', onSubmitFeedsForm);
$('.feeds-form .textinput').on({
'keyup': onKeyUpTextInput,
'change': onKeyUpTextInput 
});

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

function onSubmitFeedsForm(event) {
event.preventDefault();
console.log($(this).serialize());
var form = $(event.target);
var textInput = form.find('.textinput');
var hiddenField = form.find('input[name="post_comment"]');

$.ajax({
  type: 'POST',
  url: "{% url 'site:home' %}",
  data: form.serialize(),
  dataType: 'json',
  beforeSend: function() {
    form.find('.submit').attr('disabled', true);
  },
  success: function(response) {
    $('#newfeeds-form' + hiddenField.val()).html(response.form);
    textInput.val(''); 

    var numberOfCommentsElement = $('#number-of-comments');
    numberOfCommentsElement.text(parseInt(numberOfCommentsElement.text()) + 1);
  },
  error: function(rs, e) {
    console.log(rs.resopnseText);
  },
  complete: function() {
    textInput.trigger('change');
  }
});
}

});
</script>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You don't need ajax actually, you can simply:

let value = $('myInput').val();
$('myCommentContainer').prepend(`
Format the comment as you want ${value}
`)

$('myInput').val('') // To empty the value

now call the ajax normally:

$({
type: 'POST',
  url: "{% url 'site:home' %}",
  data: form.serialize(),
  dataType: 'json',
  beforeSend: function() {
    form.find('.submit').attr('disabled', true);
  },
  success: function(response) {}
})

Done, leave the success empty appending it within the ajax success will make it slower anyway!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...