【发布时间】:2020-02-06 11:35:10
【问题描述】:
如何将 Django 模板发送到 ajax 请求并包含该模板的上下文变量?
【问题讨论】:
-
你能解释一下你想要达到什么目标吗?
-
请编辑问题以将其限制为具有足够详细信息的特定问题,以确定适当的答案。避免一次问多个不同的问题。请参阅How to Ask 页面以获得澄清此问题的帮助。
标签: django ajax django-templates
如何将 Django 模板发送到 ajax 请求并包含该模板的上下文变量?
【问题讨论】:
标签: django ajax django-templates
您可以简单地使用render:
def some_ajax_view(request):
do_stuff()
...
context = {'some_template_variable':'foo'}
return render(request, 'some_template.html, context)
现在您可以在 ajax 请求中访问模板:
$.ajax({
...
success: function(response, status, XHR) {
console.log(response); // this will print the entire html template
$('#some-element').append(response); // this will insert the template into "some-element"
});
如果你需要在你的ajax成功回调中访问上下文变量,你可以使用render_to_string:
from django.template.loader import render_to_string
from django.http import JsonResponse
def some_ajax_view(request):
do_stuff()
...
context = {'some_template_variable':'foo'}
html = render_to_string('some_template.html', context)
print(html) # this will print the entire html template
return JsonResponse({'html':html, 'context'})
如果您正在发出POST 请求,则需要在页面初始加载时添加一个 csrf 令牌(不是来自 ajax 视图):
def initial_view(request):
do_stuff()
return render(request, 'initial_template.html', context)
现在initial_template.html:
<script type="text/javascript">
window.csrf_token = "{{ csrf_token }}";
</script>
然后,在您的 ajax 调用中,您需要将其包含在请求正文中:
$.ajax({
method: 'POST',
data: {
csrfmiddlewaretoken: window.csrf_token,
some_other_data: 'foo',
...
},
success: function(response, status, XHR) {
...
});
【讨论】: