我想呈现两个不同的HTML示例,并将其作为对ajax请求的响应发回。
我认为我有这样的事情:
def getClasses(request):
User = request.user
aircomcode = request.POST.get('aircompany_choice', False)
working_row = Pr_Aircompany.objects.get(user=User, aircomcode=aircomcode)
economy_classes = working_row.economy_class
business_classes = working_row.business_class
economy = render_to_response('dbmanager/classes.html', {"classes": economy_classes}, content_type="text/html")
business = render_to_response('dbmanager/classes.html', {"classes": business_classes}, content_type="text/html")
return JsonResponse({"economy": economy,
"business": business})
有了这个,我得到了错误:
位于0x7f501dc56588的django.http.response.HttpResponse对象不是JSON可序列化的"我该如何完成任务?
在获得响应的js中,我想将接收到的HTML插入到corespoding块中。像这样:
$.ajax({ # ajax-sending user's data to get user's classes
url: url,
type: 'post',
data: {"aircompany_choice": aircompany_choice}, # send selected aircompanies for which to retrieving classes required
headers: {"X-CSRFToken":csrftoken}, # prevent CSRF attack
}).done (result) ->
add_booking_classes.find(".economy-classes").children(":nth-child(2)").html(result["economy"])
add_booking_classes.find(".business-classes").children(":nth-child(2)").html(result["business"])
答案 0 :(得分:4)
尝试Django的render_to_string
:
economy = render_to_string('dbmanager/classes.html', {"classes": economy_classes})
business = render_to_string('dbmanager/classes.html', {"classes": business_classes})
render_to_string()
加载模板,渲染它然后返回结果字符串。然后,您可以将这些结果字符串作为JSON发送。
您的最终代码现在变为:
from django.template.loader import render_to_string
def getClasses(request):
User = request.user
aircomcode = request.POST.get('aircompany_choice', False)
working_row = Pr_Aircompany.objects.get(user=User, aircomcode=aircomcode)
economy_classes = working_row.economy_class
business_classes = working_row.business_class
economy = render_to_string('dbmanager/classes.html', {"classes": economy_classes})
business = render_to_string('dbmanager/classes.html', {"classes": business_classes})
return JsonResponse({"economy": economy,
"business": business})
答案 1 :(得分:2)
render_to_response
用于呈现响应。你不想这样做;您想要渲染两个模板,并将它们放入JSON响应中。因此,请使用render_to_string
。
答案 2 :(得分:0)
您可以在上下文中发送一个,也可以在要渲染的位置发送一个。