jquery - 渲染响应不适用于 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);
});
})
});
解决方案
我建议你试试 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() 等。
推荐阅读
- python - Python中的多级登录系统随机拒绝尝试
- drupal - drupal 8:自定义字段具有多个值
- php - 如何避免 PayPal 计划重复
- html - HTML 和/或 CSS 自动生成简单的搜索过滤图像/选项
- protocol-buffers - Google protobuf 3:弃用了一个字段,但无法删除依赖项?
- hydra - Hydra 可以通过 PKCE 使用授权代码流吗?
- c# - .net Core Razor Pages 应用程序中的 Windows 身份验证
- python - 如何正确使用正则表达式匹配查找以下字符串中的前 3 个相关字母
- apache - Htaccess - 一个文件中的多个规则
- javascript - 断言正确时,TestCafe 触发了“断言错误”