【问题标题】:ajax like button djangoajax 像按钮 django
【发布时间】:2019-04-02 04:10:15
【问题描述】:

我的 ajax jquery:

 $(".likebutton").on('click', function () {
  post_id=$(this).attr('name');
  console.log('CLICKED IN LIKE');
    $.ajax({

    dataType: 'json',

    url: post_id +'/like/',
    data: {


  },
  success: function (data) {
       alert("SUCESSS");
      if (data.success) {
       console.log("SUCCESS")
        $(this).parents('.timeline-footer').html('<p class="pull-left 
   m-r-15">'+data.likecount+ 'Likes </p>'+
                 '<a class="likebutton" style="color: blue"'+
                   'href="dashboard/tasks/'+ post_id +'/like/"'+ 
  'class="m-r-15 text-inverse-lighter"><i'+
                        'class="fa fa-thumbs-up fa-fw fa-lg m-r-3"> 
 </i>'+
                    'Like</a>'+
                '<a href="dashboard/tasks/'+post_id  +'/$/" class="m- 
 r-15 text-inverse-lighter"><i'+
                        'class="fa fa-comments fa-fw fa-lg m-r-3"> 
    </i>'+
                    'Comment</a>')

        // here you update the HTML to change the active to innactive
      }else{
      console.log("ERROR");
        alert("ajax call not success.");
      }
 }
});
 });

我喜欢的模板 like_comment2.html:

<p class="pull-left m-r-15"> {{ obj.like.count }} Likes </p>

<form action="{% url 'student:like' pk=obj.id %}" method="POST">
{% csrf_token %}
 <input type="submit" value="Like" name="{{ obj.id }}" 
class="likebuttons m- 
r-15 text-inverse-lighter" {% if request.user in obj.like.all %} 
style="color: blue" {% endif %}"></input><i class="fa fa-thumbs-up fa- 
fw 
fa-lg m-r-3"></i>


</form>

我的看法:

def LikeToggleView(request,pk=None):
print("NOT AJAX")
if request.is_ajax():
    post_id = request.POST.get('post_id')
    response_data = {}
    obj = get_object_or_404(Task, pk=post_id)

    user = request.user

    print("AJAX LIKE")

    if user in obj.like.all():
             obj.like.remove(user)
             note = Notification.objects.create(sender=user, task=obj, 
 notification = user.username + ' Disliked Your Post ' + obj.title)
             note.receiver.add(obj.student)
    else:
             obj.like.add(user)
             note = Notification.objects.create(sender=user, task=obj, 
  notification = user.username + '  Liked Your Post ' + obj.title)
             note.receiver.add(obj.student)



    response_data['likecount'] = obj.like.count

    return JsonResponse(response_data)

我想使用 ajax 更新模板中的点赞数。似乎它没有进入 ajax 调用:它在终端中打印“Not AJax”

我的 urls.py

url(r'^dashboard/tasks/(?P<pk>\d+)/like/$', views.LikeToggleView, 
name='like'),

控制台显示错误: 获取http://localhost:8000/student/dashboard/tasks/154/like/ 404(未找到) http://localhost:8000/student/dashboard/tasks/154/like/404(未找到)

14:21:37.896 :8000/student/dashboard/tasks/154/like/:1 POST http://localhost:8000/student/dashboard/tasks/154/like/ 500(内部服务器错误) 当我点击喜欢按钮时,它也会触发 jquery onclick 两次

urls.py:

from django.conf.urls import url
from . import views

app_name = 'student'

urlpatterns=[
url(r'^dashboard/tasks/$',views.StudentDashView,name='dashboard'),
url(r'^dashboard/tasks/ajax/reload/$', views.ajax_change_status, 
name='ajax_change_status'),

url(r'^dashboard/tasks/(?P<pk>\d+)/$', views.TaskDetailView, 
name='task-detail'),
url(r'^dashboard/tasks/(?P<pk>\d+)/like/$', views.LikeToggleView, 
name='like'),
url(r'^add-mentor/$',views.AddMentor,name='add_mentor'),
url(r'^trainer-profile/(?P<trainer_id>\d+)/$', 
views.TrainerPublicProfile, name='trainer_public_profile'),
url(r'^add-as-mentor/(?P<pk>\d+)/$', views.AddAsMentor, 
name='add_as_mentor'),
url(r'change-as-mentor/(?P<pk>\d+)/$', views.ChangeAsMentor, 
name='change_as_mentor'),
url(r'^accept-to-hub/(?P<pk>\d+)/(?P<notify>\d+)/$', views.AcceptHub, 
name='accept_hub'),
url(r'^reject-to-hub/(?P<pk>\d+)/(?P<notify>\d+)/$', views.RejectHub, 
name='reject_hub'),
url(r'^accept-mentor/(?P<pk>\d+)/$', views.AcceptMentor, 
name='accept_as_mentor'),
url(r'^reject-mentor/(?P<pk>\d+)/$', views.RejectMentor, 
name='reject_as_mentor'),
url(r'^promote-to-excom/(?P<user>\d+)/$', views.PromoteExcom, 
name='promote'),
url(r'^depromote-to-excom/(?P<user>\d+)/$', views.DePromoteExcom, 
name='depromote'),
url(r'^remove-from-hub/(?P<user>\d+)/$', views.RemoveFromHub, 
name='remove_from_hub'),

url(r'^view-hubs/$', views.HubListView, name='view_all_hubs'),
url(r'^join-hub/(?P<pk>\d+)/$', views.JoinHub, name='join_hub'),

# url(r'^dashboard/tasks/(?P<task_id>\d+)/like/$', views.Tasklike, 
name='task-like'),
url(r'^level/$', views.StudentLevelListView, name='level'),
url(r'^level/(?P<pk>\d+)/$', views.StudentLevelDetailView, 
name='level-detail'),
url(r'^level/(?P<pk>\d+)/(?P<todo_id>\d+)/$', views.TaskCreateView, 
name='task-form'),
url(r'^hub/$', views.StudentHubListView, name='hub'),
url(r'^subscribe/member/$',views.MemberPay,name='member'),
url(r'^subscribe/fellow/$', views.FellowPay, name='fellow'),
url(r'^payment-member/success$', views.payment_success_member,  
name="payment_success_member"),
url(r'^payment-member/failure$', views.payment_failure_member, 
name="payment_failure_member"),
url(r'^payment-fellow/success$', views.payment_success_fellow, 
name="payment_success_fellow"),
url(r'^payment-fellow/failure$', views.payment_failure_fellow, 
name="payment_failure_fellow"),

]

js:

 $(".likebutton").on('click', function (event) {
 event.preventDefault();
 post_id=$(this).attr('value');
  console.log('CLICKED IN LIKE');
    $.ajax({
type:'post',
    url: post_id+'/like/',
    data: {
  csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val()

    },

 success: function (data) {
       alert("SUCESSS");
      if (data.success) {
       console.log("SUCCESS")
        $(this).parents('.timeline-footer').html('<p class="pull-left 
  m-r-15">'+data.likecount+ 'Likes </p>'+
                 '<a class="likebutton" style="color: blue"'+
                   'href="dashboard/tasks/'+ post_id +'/like/"'+ 
 'class="m-r-15 text-inverse-lighter"><i'+
                        'class="fa fa-thumbs-up fa-fw fa-lg m-r-3"> 
 </i>'+
                    'Like</a>'+
                '<a href="dashboard/tasks/'+post_id  +'/$/" class="m- 
 r-15 text-inverse-lighter"><i'+
                        'class="fa fa-comments fa-fw fa-lg m-r-3"> 
</i>'+
                    'Comment</a>')

        // here you update the HTML to change the active to innactive
      }else{
      console.log("ERROR");
        alert("ajax call not success.");
      }
},
     crossDomain: false


});
 });



 $(".likebuttons").on('click', function (event) {
  event.preventDefault();
 post_id=$(this).attr('value');
 console.log('CLICKED IN LIKE');
    $.ajax({
     headers: {'X-Requested-With': 'XMLHttpRequest'},
 type:'post',
    url: 'like/',
    data: {
  csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val()

    },

 success: function (data) {
       alert("SUCESSS");
      if (data.success) {
       console.log("SUCCESS")
        $(this).parents('.timeline-footer').html('<p class="pull-left 
 m-r-15">'+data.likecount+ 'Likes </p>'+
                 '<a class="likebutton" style="color: blue"'+
                   'href="dashboard/tasks/'+ post_id +'/like/"'+ 
 'class="m-r-15 text-inverse-lighter"><i'+
                        'class="fa fa-thumbs-up fa-fw fa-lg m-r-3"> 
</i>'+
                    'Like</a>'+
                '<a href="dashboard/tasks/'+post_id  +'/$/" class="m- 
 r-15 text-inverse-lighter"><i'+
                        'class="fa fa-comments fa-fw fa-lg m-r-3"> 
</i>'+
                    'Comment</a>')

        // here you update the HTML to change the active to innactive
      }else{
      console.log("ERROR");
        alert("ajax call not success.");
      }
},

    crossDomain: false


 });
});

我在这里添加了类似的部分:

 <div class="timeline-footer">

   {% include 'like_comment2.html' %}
    <a href="javascript:;" class="m-r-15 text-inverse-lighter"><i 
 class="fa fa-comments fa-fw fa-lg m-r-3"></i>
        Comment</a>
  </div>

【问题讨论】:

    标签: python jquery ajax django


    【解决方案1】:

    它实际上并没有触发两次,它触发了 Ajax 帖子,但随后浏览器立即将页面提交到相同的 URL。

    你需要在你的 JS 中阻止默认的提交动作:

    $(".likebutton").on('click', function(event) {
        event.preventDefault();
       ...
    });
    

    【讨论】:

    【解决方案2】:

    这是最终的工作代码:

    Javascript:

    $(document).on('click','.likebutton',function(event)  {
    event.preventDefault();
    post_id=$(this).attr('value');
    console.log('CLICKED IN LIKE');
        $.ajax({
        url: post_id+'/like/',
     type:'post',
    
        data: {
      csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val()
    
     },
    
      success: function (data) {
    
           console.log("SUCCESS")
           console.log(data);
            console.log($(this).closest("div").prop("class"));
            $(this).closest('div').html(data)
    
            // here you update the HTML to change the active to innactive
    
      }.bind(this),
     error: function(xhr, status, error) {
     var err = JSON.parse(xhr.responseText);
     alert(err.Message);
    }
    
     });
     });
    

    我的功能:

     def LikeToggleView(request,pk=None):
    
    
        obj = get_object_or_404(Task, pk=pk)
    
        user = request.user
    
    
        if user in obj.like.all():
                 obj.like.remove(user)
                 note = Notification.objects.create(sender=user, task=obj, 
      notification = user.username + ' Disliked Your Post ' + obj.title)
                 note.receiver.add(obj.student)
        else:
                 obj.like.add(user)
                 note = Notification.objects.create(sender=user, task=obj, 
      notification = user.username + '  Liked Your Post ' + obj.title)
                 note.receiver.add(obj.student)
    
    
        if request.is_ajax():
         print("AJAX LIKE")
         context={
            'obj':obj,
    
         }
         html = render_to_string('like_comment.html', context, request=request)
         return HttpResponse(html)
    

    like_comment.html:

     {% load static %}
    
     <p class="pull-left m-r-15"> {{ obj.like.count }} Likes </p>
    
     <form action="{% url 'student:like' pk=obj.id %}" method="POST">
     {% csrf_token %}
     <a href="" type="submit" value="{{ obj.id }}" name="post_id"   
     class="likebutton m-r-15 text-inverse-lighter" {% if request.user in o 
    Obj.like.all %} style="background: blue" {% endif %}">Like</a><i class="fa fa- 
    thumbs-up fa-fw fa-lg m-r-3"></i>
    
    
    </form>
     <a href="{% url 'student:task-detail' obj.id %}" class="m-r-15 text-inverse- 
     lighter"><i
                            class="fa fa-comments fa-fw fa-lg m-r-3"></i>
                        Comment</a>
    

    【讨论】:

      猜你喜欢
      • 2017-08-24
      • 2012-11-23
      • 1970-01-01
      • 2011-09-03
      • 2014-09-20
      • 1970-01-01
      • 1970-01-01
      • 2017-03-26
      • 1970-01-01
      相关资源
      最近更新 更多