首页 > 解决方案 > 渲染响应不适用于 jquery ajax 请求

问题描述

我向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

标签: jqueryajaxdjangorender-to-response

解决方案


我建议你试试 django 大括号。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() 等。


推荐阅读