我解决了这个问题,只要DOM准备就绪,然后重新加载AJAX,就可以通过计算令牌的值。
javascript代码使用reload_ajax()函数来处理标记,以及在初始页面加载和随后的AJAX调用时需要刷新的任何其他事物。
<script type="text/javascript">
function reload_ajax() {
// Useful on initial page load, and after calling AJAX.
$("input#token").val("{{ csrf_token }}");
}
$(document).ready(function() {
$("form#stats").unbind("submit"); // Prevents calling document-ready multiple times
$("form#stats").submit(function(event) {
event.preventDefault();
$.ajax({
type:"POST",
url: $(this).attr("action"),
data: $(this).serialize(), // Serialize the form
dataType: "json",
success: function(response){
$("#stats_ajax").html(response.html); // Object to refresh after AJAX
reload_ajax();
}
});
return false;
});
reload_ajax();
});
</script>
我使用两个HTML文件, 在main.html中,我的JavaScript代码之上,并执行以下操作:
<div id="stats_ajax">
{% include "stats_ajax.html" %}
</div>
在stats_ajax.html,我有实际的形式(加上其他的事情,我需要刷新)
<form id="stats" action="/main/" method="post">
<!-- The value will be inserted when the DOM reloads. -->
<input id="token" type="hidden" name="csrfmiddlewaretoken" value="" />
<!-- Other input elements -->
<button type="submit">Submit</button>
</form>
在我的views.py文件,
# Not all imports may be needed for this example
from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.template.loader import render_to_string
import json
def main(request):
# This request should only be posting AJAX
if request.is_ajax():
data = {}
data["message"] = "Awesome"
# This is the template to load on the DOM object to update
html = render_to_string("stats_ajax.html", data)
res = {"html": html}
return HttpResponse(json.dumps(res), mimetype='application/json')
# Handle GET to this view
return redirect("/main")
最后,我的urls.py有
# Replace "application_name" with your own value
url(r'^main', 'application_name.views.main'),
你可能想看看csrf_exempt [这里](https://docs.djangoproject.com/en/1.2/ref/contrib/csrf/) –
已经看到了,如果你看看我在bpaste上的代码,它几乎是一样的。区别在于我将其作为外部.js文件包含在内。由于我想共享该功能,并且每次在每个模板中执行ajax请求时都不包含相同的代码。也许这是问题?在使用ajax时,在哪里放置csrf_token?以及在哪里放置getCookie代码(即:只有当我做错了)? – Aki