如何将Django模板发送到ajax请求并包括该模板的上下文变量?
答案 0 :(得分:1)
您可以简单地使用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) {
...
});