简体   繁体   English

使用 ajax 在 django 中制作类似按钮

[英]make like button in django using ajax

How I can make like button in Django using ajax my html, I need to click like button without reload the page, The ajax function didn't work How I can make like button in Django using ajax my html, I need to click like button without reload the page, The ajax function didn't work

  <form method="POST" action="{% url 'video:like' video.pk %}">
  {% csrf_token %}
  <input type="hidden" class="likin" name="next" value="{{ request.path }}">
  <button class="remove-default-btn" type="submit">
      <i class="fa fa-thumbs-up" aria-hidden="true"><span>{{ video.likes.all.count }}</span></i>
  </button>

JavaScript JavaScript

    $('.likin').click(function(){
$.ajax({
         type: "POST",
         url: "{% url 'video:like' video.pk %}",
         data: {'content_id': $(this).attr('name'),'operation':'like_submit','csrfmiddlewaretoken': '{{ csrf_token }}'},
         dataType: "json",
         success: function(response) {
          selector = document.getElementsByName(response.next);
                if(response.liked==true){
                  $(selector).css("color","blue");
                }
                else if(response.liked==false){
                  $(selector).css("color","black");
                }


          }

    });

})

You have added an event on the buttons click but that will not stop the forms submission (your button has type="submit" and submits the form).您已在按钮单击上添加了一个事件,但这不会停止 forms 提交(您的按钮具有type="submit"并提交表单)。 Instead of adding an event on the button's click instead add an event on the forms submission and prevent it.而不是在按钮的单击上添加一个事件,而是在 forms 提交上添加一个事件并阻止它。 Next submit it yourself using ajax.接下来使用 ajax 自己提交。

First in your form tag add an id:首先在您的表单标签中添加一个 id:

<form method="POST" action="{% url 'video:like' video.pk %}" id="my-like-form">

Next add an event to the form submission:接下来在表单提交中添加一个事件:

$("#my-like-form").submit(function(e){
    e.preventDefault(); // Prevent form submission
    let form = $(this);
    let url = form.attr("action");
    $.ajax({
        type: "POST",
        url: url,
        data: form.serialize(),
        dataType: "json",
        success: function(response) {
            selector = document.getElementsByName(response.next);
            if(response.liked==true){
                $(selector).css("color","blue");
            } else if(response.liked==false){
                $(selector).css("color","black");
            }
        }
    })
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM