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 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置