我通过在 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>
In my views.py file,
# 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")
Finally, my urls.py has
# Replace "application_name" with your own value
url(r'^main', 'application_name.views.main'),