开发者

Django ajax 'like' button using Jquery?

I want to implement a ajax 'like' button which should increase the like count and not refresh the whole page. I am new to ajax so please help.

urls.py:

(r'^like/(\d+)/$',like),

Below is my views code for like:

def like(request,feedno):
  feed=Feed.objects.get(pk=feedno)
  t=request.META['REMOTE_ADDR']
  feed.add_vote(t,+1)
  vote, created = Vote.objects.get_or_create(

          feed=feed,
          ip=t,
          )

  feed.likecount+=1
  feed.save()
  if 'HTTP_REFERER' in request.META:
    return HttpResponseRedirect(request.META['HTTP_REFERER'])
  return HttpResponseRedirect('/')

Below is my html(like div):

<div class="like_abuse_box">
  <p>Likes:<b>{{vote.feed_set.count}}</b> ||
   <a class="like" href="/like/{{feed.id}}/">Like</a> | 
   <a class="abuse" href="/abuse/{{feed.id}}/">Abuse</a> || </p>
</div>

What code should I include to only refresh that par开发者_Python百科ticular div and updated like count be shown without the whole page getting reloaded. Need Help. Thanks.


Haven't tested it athough something like that should work. Edit: tested and works, now for multiple elements on a webapage

Javascript

$("a.like").click(function(){
    var curr_elem = $(this) ;
    $.get($(this).attr('href'), function(data){
        var my_div = $(curr_elem).parent().find("b");
        my_div.text(my_div.text()*1+1);     
    }); 
    return false; // prevent loading URL from href
});

Django view

You can add if request is Ajax with:

if request.is_ajax():


First thing: put an id on the html element where the content to be injected.

<div class="like_abuse_box">
  <p>Likes:<b id="like_count">{{vote.feed_set.count}}</b> ||
   <a class="like" href="/like/{{feed.id}}/">Like</a> | 
   <a class="abuse" href="/abuse/{{feed.id}}/">Abuse</a> || </p>
</div>

second, in your view you need to return the latest like count. You can't just locally update the count, since there is a chance that someone else may have updated the like count as well.

Lastly. in your page include the jquery

$("a.like").bind("click", function(){
    var link = $(this).attr("href");
    $.get(link, function(data) {
        $(this).parent("div").children('b#like_count').html(data);
    });
});

I am not quite certain about the parent child selector, to navigate from hyper linked clicked to its corresponding like count. You may have to play around with JQuery selector to get it right.

ALso, if you are using POST for your view, replace $.get with $.post

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜