【发布时间】:2012-12-29 09:13:23
【问题描述】:
我正在尝试使用来自 javascript 的 $post 请求到我的 django 模板中,但是我缺少一些东西,因为它不起作用。
我会告诉你我的代码:
这是模板:
//TEMPLATE
//This code will send a string to django "views.py" file,
//then it will show a pop up message from the data retreived from "views.py"
function test_post(){
$.post("/xhr_test",
{name: "Monty", food: "Spam", csrftoken : "{{ csrf_token }}" },
function(data) {
alert(data)
;});
};
这是views.py:
// VIEWS.PY
//Depending on the type of request it will send a message or another.
def xhr_test(request):
if request.is_ajax():
if request.method == 'GET':
message = "This is an XHR GET request"
elif request.method == 'POST':
message = "This is an XHR POST request"
# Here we can access the POST data
print request.POST
else:
message = "No XHR"
return HttpResponse(message)
此代码未按应有的方式显示“这是一个 XHR POST 请求”消息。但是,当使用 $get 请求时,它会显示“这是一个 XHR GET 请求”消息。
thread 中也有类似的疑问。即使我使用了那里提供的答案,代码也不起作用。
我猜答案一定与“{{ csrf_token }}”有关,但不确定如何...
我们将不胜感激任何类型的帮助。
【问题讨论】:
-
你如何填充
csrf_token?