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

ε祈祈猫儿з 提交于 2020-01-07 03:21:50

问题


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.

来源:https://stackoverflow.com/questions/42126427/js-stops-working-on-child-template-when-i-perform-an-ajax-call-to-change-the-que

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!