weixin_33712987 2017-12-07 18:02 采纳率: 0%
浏览 21

像Ajax一样的按钮

I am trying to create a like button with ajax.

This is my architecture:

models.py

class Comentario (models.Model):
    titulo = models.CharField(max_length=50)
    texto = models.CharField(max_length=200)
    autor = models.ForeignKey (Perfil, null=True, blank=True, on_delete=models.CASCADE)
    fecha_publicacion = models.DateTimeField(auto_now_add=True)
    tag = models.ManyToManyField(Tags, blank=True)
    slug = models.SlugField(null=True)
    likes = models.ManyToManyField(Perfil, blank=True, related_name="likes")

    def __str__(self):
        return (self.titulo)

    @property
    def total_likes(self):
        return self.likes.count()

    def save(self, *args, **kwargs):
        self.slug = slugify(self.titulo)
        super(Comentario, self).save(*args, **kwargs)

views.py

def like(request):
    if request.method == 'POST':
        perfil = request.user
        slug = request.POST.get('slug', None)
        comentario = get_object_or_404(Comentario, slug=slug)

        if comentario.objects.filter(id=user.id).exists():
            comentario.likes.remove(user)

        else:
            comentario.likes.add(user)


    contexto = {'likes_count': comentario.total_likes }
    return HttpResponse(json.dumps(contexto), content_type='application/json')

urls.py

url(r'^like$', login_required(like), name='like'),

html

<input type="button" id="like" name="{{ company_slug }}" value="Like" />
<script>
$('#like').click(function(){
      $.ajax({
               type: "POST",
               url: "{% url 'home:like' %}",
               data: {'slug': $(this).attr('titulo'), 'csrfmiddlewaretoken': '{{ csrf_token }}'},
               dataType: "json",
               success: function(response) {
                      alert(response.message);
                      alert(' likes count is now ' + response.likes_count);
            },
                error: function(rs, e) {
                       alert(rs.responseText);
            }
      }); 
})
</script>

When I push the button like it does not do anything. The console tells me:

POST htt jquery.min.js:4 p:/127.0.0.1.8000/home/like/404 (not found)

and: http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js

What is the problem?

  • 写回答

2条回答 默认 最新

  • weixin_33725270 2017-12-07 18:43
    关注

    #1

    As I can see you use jquery-3.2.1.slim.min.js. This (slim) version excludes ajax module!

    https://blog.jquery.com/2017/03/16/jquery-3-2-0-is-out/

    Slim build

    Sometimes you don’t need ajax, or you prefer to use one of the many standalone libraries that focus on ajax requests. And often it is simpler to use a combination of CSS and class manipulation for all your web animations. Along with the regular version of jQuery that includes the ajax and effects modules, we’ve released a “slim” version that excludes these modules.

    #2

    You use wrong url as I can see. In your html part it's {% url 'home:listar' %}, given urls.py contains only name='like'

    评论

报告相同问题?

悬赏问题

  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件