我正在进行下面的ajax调用:
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'),
我得到了#34;禁止(CSRF令牌丢失或不正确。):/ issuebook&#34; ajax调用错误。
ajax调用中的csrf标记呈现为:
var data_dict = {'user':{{ user.id }}, 'bookId':that.id, 'csrfmiddlewaretoken':'fSSdu8dJ4FO6FvDz8eU5ISzOewRYyGbC'};
$.ajax({
type: 'POST',
url:"/issuebook",
data:data_dict,
contentType: false,
success:function(response)
{
}
});
答案 0 :(得分:6)
此错误是由ajax函数中的processData
和contentType
选项引起的。删除这两个选项将解决问题。
<强>说明:强>
必须将参数作为urlencoded with Content-Type application/x-www-form-urlencoded
发送到Django。然而,如果您设置processData: false
它不会对POST parmaters进行编码,contentType: false
会将ajax POST请求发送为text/plain
。