我试图在django项目中使用jquery处理ajax POST请求。
但是我遇到了一个没有具体信息的错误。
我想下面的一些列表是错误原因的假设。
此外,这是额外的代码。
def add_to_cart(request):
quantity = request.POST.get('quantity')
product_id = request.POST.get('product_id')
return HttpResponse(json.dumps({
"product_id" : product_id,
"quantity" : quantity,
}),content_type="application/json")
# output >>> {"product_id":null, "quantity":null} shops/views.py
url(r'^detail/(?P<product_id>[0-9]+)$', views.product_detail, name="detail"),
url(r'^detail/add_to_cart$', views.add_to_cart, name="add_to_cart"),
url(r'^cart$', views.cart, name="cart"),
url(r'^cart/del_from_cart$', views.del_from_cart, name="del_from_cart"),shops/urls.py
虽然传递给django视图的参数很简单,但我想使用POST请求。
我在使用django-1.7版本。
请帮帮我。
发布于 2015-01-12 20:09:47
默认情况下,CSRF是在Django中激活的,因此为了在jquery请求中使用它:
在您的JS文件中:
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
var csrftoken = getCookie('csrftoken');
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});上面的内容将在您的请求中添加CSRF,Django在使用POST时希望这样做。您可以在正式文档中找到更多信息:https://docs.djangoproject.com/en/1.7/ref/contrib/csrf/
https://stackoverflow.com/questions/27909584
复制相似问题