问题描述
我正在像下面这样进行ajax调用:
I am making ajax call like below:
var data_dict = {'user':{{ user.id }}, 'bookId':that.id, 'csrfmiddlewaretoken': '{{ csrf_token }}'};
$.ajax({
type: 'POST',
url:"/issuebook",
data:data_dict,
processData: false,
contentType: false,
success:function(response)
{
}
});
urls.py是:
urlpatterns = [
url(r'^$',views.checkLogin,name='checklogin'),
url(r'^mylibrary/(?P<pk>\d+)/(?P<user_name>[\w\-]+)$',login_required(views.MyLibrary.as_view()),name='mylibrary'),
url(r'^centrallibrary/(?P<pk>\d+)/(?P<user_name>[\w\-]+)$',login_required(views.CentralLibrary.as_view()),name='centrallibrary'),
url(r'^issuebook$',login_required(views.IssueBookView.as_view()),name='issuebook'),
]
我在ajax调用中收到禁止(CSRF令牌丢失或不正确。):/ issuebook错误。
I am getting "Forbidden (CSRF token missing or incorrect.): /issuebook" error on ajax call.
ajax调用中的csrf令牌呈现为:
The csrf token in ajax call is getting rendered as:
var data_dict = {'user':{{ user.id }}, 'bookId':that.id, 'csrfmiddlewaretoken':'fSSdu8dJ4FO6FvDz8eU5ISzOewRYyGbC'};
$.ajax({
type: 'POST',
url:"/issuebook",
data:data_dict,
contentType: false,
success:function(response)
{
}
});
推荐答案
此错误是由引起的Ajax函数中的processData
和 contentType
选项。删除这两个选项将解决此问题。
This error is caused by processData
and contentType
options in your ajax function. Removing these two options will fix the issue.
说明:
参数必须以Content-Type的urlencode发送给Django。 application / x-www-form-urlencoded
。而如果您设置 processData:false
不会对POST参数进行编码,而 contentType:false
将发送ajax POST请求为文本/纯文本
。
Explanation:The arguments must be sent to Django as urlencoded with Content-Type application/x-www-form-urlencoded
. Whereas, if you set processData: false
it won't encode the POST parmaters and contentType: false
will send ajax POST request as text/plain
.
这篇关于禁止(CSRF令牌丢失或不正确。):的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!