通过我的AJAX帖子,我需要一些帮助来遵守Django的CSRF保护机制.我按照这里的说明做了:
http://docs.djangoproject.com/en/dev/ref/contrib/csrf/
我复制了他们在该页面上的AJAX示例代码:
http://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax
我在xhr.setRequestHeader
呼叫前打印了getCookie('csrftoken')
的内容,并在其中填充了一些数据.我不确定如何验证令牌是否正确,但我很高兴它正在查找并发送一些东西.
但Django仍然拒绝我的AJAX帖子.
以下是我的JavaScript:
$.post("/memorize/", data, function (result) {
if (result != "failure") {
get_random_card();
}
else {
alert("Failed to save card data.");
}
});
以下是我从Django身上看到的错误:
[23/Feb/2011 22:08:29]"POST/memory/HTTP/1.1"403 2332
我肯定我错过了什么,也许很简单,但我不知道是什么.我四处搜索了一下,看到了一些关于通过csrf_exempt
decorator关闭CSRF查看的信息,但我觉得这很不吸引人.我已经try 过了,而且效果很好,但如果可能的话,我宁愿让我的帖子按照Django设计的预期工作.
为了以防万一,以下是我的观点的要点:
def myview(request):
profile = request.user.profile
if request.method == 'POST':
"""
Process the post...
"""
return HttpResponseRedirect('/memorize/')
else: # request.method == 'GET'
ajax = request.GET.has_key('ajax')
"""
Some irrelevent code...
"""
if ajax:
response = HttpResponse()
profile.get_stack_json(response)
return response
else:
"""
Get data to send along with the content of the page.
"""
return render_to_response('memorize/memorize.html',
""" My data """
context_instance=RequestContext(request))
谢谢你的回复!