渲染到响应不适用于jquery ajax请求

问题描述 投票:2回答:1

我向jquery发送了一个ajax get请求但是render_to_response不起作用我在下面添加了代码print("request is : ", self.request)但是打印了空

请让我知道如何修复或如何调试

谢谢〜!

博客\ views_cbv.py

class PostDetailView(DetailView):
print("detail view")
    model = Post
    def render_to_response(self, context):
        print("request is : ", self.request)
        if self.request.is_ajax():
            print("request is ajax ")
            return JsonResponse({
                'title': self.object.title,
                'summary': truncatewords(self.object.content, 100),
            })
        return super().render_to_response(context)

post_detail = PostDetailView.as_view()

博客/ post_list.html

$(document).ready(function () {
    $(document).on('click', '#post_list a', function (e) {
        e.preventDefault();
        const detail_url = $(this).attr("href");
        <!-- alert(detail_url) -->
        console.log("detail_url : ", detail_url )

        $.get(detail_url)
            .done((json_obj) => {
                var $modal = $("#post-modal");
                console.log("json_obj : ", json_obj)
                $modal.find('.modal-title').html(json_obj.title);
                $modal.find('.modal-body').html(json_obj.summary);
                $modal.find('.btn-detail').attr('href', detail_url)
                $modal.modal();
            })
            .fail((xhr, textStatus, error) => {
                alert('failed : ', error);
            });

    })
});

github:https://github.com/hyunsokstar/ask_class

jquery ajax django render-to-response
1个回答
1
投票

我建议你试试django braces。 https://django-braces.readthedocs.io/en/latest/。它具有ajax的内置函数

from braces.views import AjaxResponseMixin
from braces.views import JsonRequestResponseMixin

class PostDetailAjaxView(AjaxResponseMixin, JsonRequestResponseMixin, View):

    def get_ajax(self, request, *args, **kwargs):
        post_pk = request.GET.get('pk', None)
        post = Post.objects.get(pk=post_pk)

        data = {
             'title': post.title,
             'summary': truncatewords(post.content, 100)
        }
        return self.render_json_response(data)

我对模型一无所知,所以我只是用你的例子作为参考。然后你可以为PostDetailAjaxView创建一个单独的url。您现在可以使用GET作为方法通过jquery调用它。如果要使用其他方法,可以使用post_ajax(),put_ajax(),delete_ajax()等。

© www.soinside.com 2019 - 2024. All rights reserved.