Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
283 views
in Technique[技术] by (71.8m points)

jquery - JS stops working on child template when I perform an AJAX call to change the queryset

My comments.html child template looks like this:

<div class="commentsContainer">
    {% for comment in comment_list %} 

    ...


        {{ comment.text }} 

    ...

    {%  endfor %}

</div>

When I click on a button I call this AJAX function:

$('.comments_new').on('click', function() {
    $.ajax({
        type: 'GET',
        url: '/new_comments/',
        data: {
        },
        success: function (data) {
            $('.commentsContainer ').replaceWith(data);
        }
    })
});

which calls this view to change the queryset (the inital queryset is comment_list = Comment.objects.filter().order_by('-score__upvotes'):

def new_comments(request):
    if request.is_ajax():
        comment_list = Comment.objects.filter().order_by('-timestamp')
         html = {'comment_list': render_to_string('comments.html', {'comment_list': comment_list})}

         return JsonResponse(html)

This successfully swaps the querysets, however for some reason no javascript works on the newly loaded template/queryset. Can somebody tell me why this happens and how I can fix it?

PS: it sometimes gives this error in my terminal when the call is made: UserWarning: A {% csrf_token %} was used in a template, but the context did not provide the value. This is usually caused by not using RequestContext.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...