简体   繁体   中英

Django Make Button Ajax

I have a button that increments an upvote. I'd like to make the button with ajax so it does not reload the page. I am trying to follow this , but my button uses <a type="button"> . Is this an issue with my html ?

views.py

@login_required
def upvote(request):
    recommendation_id = None
    if request.method == 'GET':
        #recommendation_id = request.GET['recommendation_id']
        recommendation_id = request.POST.get('recommendation_id', False)
    upvotes = 0
    if recommendation_id:
        recommendation = coremodels.Recommendation.objects.get(id=int(recommendation_id))
        user = request.user
        recommendation.votes.up(user)
        upvotes = recommendation.votes.count()
    return HttpResponse(upvotes)

urls.py

url(r'^upvote/', coreviews.upvote, name='upvote'),

html:

<a type="button" id="upvotes" data-recommendation="{{ recommendation.id }}" href="{% url 'upvote' %}" class="btn btn-primary pull-right"><span class="glyphicon glyphicon-thumbs-up"></span>Upvote</a>

ajax.js

$('#upvotes').click(function(event){
    event.preventDefault();
    var recommendation = $(this).attr("data-recommendation");
    $.get('/upvote/', {recommendation_id: recommendation}, function(data){
               $('#upvotes').hide();
    });
});

Current Error:

The page is still reloading on click. The views.py request.GET['recommendation_id'] is unsuccessful.

在此处输入图片说明

Your page is reloading because you have event.preventDefault but it's not attached to any event. You have to put in the function as I did below

$('#upvotes').click(function(event){
    event.preventDefault();
    var recommendation = $(this).attr("data-recommendation");
    $.get('/upvote/', {recommendation: recommendation}, function(data){
               $('#like_count').html(data);
               $('#upvote').hide();
    });
});

or remove all the events and use return false at the bottom of the function.

$('#upvotes').click(function(){
    var recommendation = $(this).attr("data-recommendation");
    $.get('/upvote/', {recommendation: recommendation}, function(data){
               $('#like_count').html(data);
               $('#upvote').hide();
    });

    return false;
});

Also, you have no data-recommendation attribute in your upvotes button markup. If you look at the example you're trying to use, you'll see the author has it in this line:

<button id="likes" data-catid="{{category.id}}" class="btn btn-primary" type="button">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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