当传递 X-CSRFToken 标头或将 POST 数据中的 csrfmiddlewaretoken 发送到我的视图时,它完全跳过 ajax 处理程序并直接进入索引/基础视图。
Javascript:
$.post("/action/register", {
name: $('#input_name').val(),
email: $('#input_email').val(),
csrfmiddlewaretoken: '{{ csrf_token }}'
}, function(data) {
var response;
try {
response = JSON.parse(data.toString());
} catch(e) {
response = {"status":"error", "message":"Please try again later, we're having some tech issues!"};
}
// ... process some stuff, the callback works which is good
看法:
def handle_register(req):
''' Request handler pyfor registration, should return JSON for the AJAX request. '''
if req.is_ajax():
return validate_and_register(req)
else:
return HttpResponse('{"status":"error","message":"Invalid request."}')
网址.py:
from django.conf.urls.defaults import *
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^action/register$', 'views.handle_register', name='handle_register'),
url(r'^admin/', include(admin.site.urls)),
url(r'^.*$', 'views.handle_home', name='handle_home'),
)
当我不通过标头时,我得到一个 403 (CSRF_VERIFICATION_FAILED)。当我传递适当的标头(在多个浏览器中确认)时,它会跳过 /action/register 处理程序并直接进入“handle_home”视图。
我被困住了!