我的 jquery 看起来像这样:
$.ajax({
url:"/process_values/",
type: "POST",
data: {values:['1','2']},
success:function(response){
alert("success: " + response);
},
error:function (xhr, textStatus, thrownError){
alert("xhr status: " + xhr.statusText);
},
});
我的 django View 如下所示:
@csrf_protect
def process_values(request):
# do stuff
print 'complete'
return HttpResponse("success", mimetype="application/html")
View 执行正确,但错误回调总是在完成时调用。知道这是为什么吗?
更新:对于那些提出 CSRF 问题的人。事实并非如此,我正在使用标准 javascript 来设置该 cookie,并且我可以在 django 端的请求中看到 token 。
UPDATE2:我刚刚意识到我的函数中还有其他东西调用了这个 ajax 调用,从而改变了行为。我有一个使用以下方法编写的重定向:
document.location.href="/main/";
当我注释掉这一行时,会调用成功回调。哇,没想到这会有什么不同。有人知道为什么这会导致失败吗?已将此问题移至 here因为这是一个不同的问题。结束这个问题。
最佳答案
您需要在发布数据中传递csrf token ,或者使 View @csrf_exempt
。
你可以这样做:
$.ajax({
url:"/process_values/",
type: "POST",
data: {values:['1','2'], csrfmiddlewaretoken: $("input[name=csrfmiddlewaretoken]").val()},
success:function(response){
alert("success: " + response);
},
error:function (xhr, textStatus, thrownError){
alert("xhr status: " + xhr.statusText);
},
});
关于jquery - 为什么我的 jquery ajax 发布到 django View 总是导致错误回调执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7688447/