我解決了這個問題,只要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