当前位置: 动力学知识库 > 问答 > 编程问答 >

python - Django POST method failed to get data from ajax request

问题描述:

I'm trying to get data from ajax request using my view class. BUt on printing the Query dict, I'm getting an empty dictionary.. I already added code related to csrf.

ajax request,

$.ajax({

type: "POST",

url: "/categories/",

contentType: 'application/json',

data: JSON.stringify({"category_id": id, "category_name": name}),

success: function(data) {

$('#category-modal').modal('toggle');

}

urls.py

 urlpatterns = [

url(r'^categories/', CategoryView.as_view(), name='Categories'),

]

views.py

class CategoryView(TemplateView):

template_name = 'categories.html'

def get(self, request, *args, **kwargs):

items = CategoryQuery.get_all_categories()

context = {

'items': items,

}

return self.render_to_response(context)

def post(self, request, *args, **kwargs):

query_dict = request.POST

converted_dict = query_dict.dict()

print converted_dict

网友答案:

request.POST is for form-encoded data. You have JSON; you should access request.body and deserialize it via json.loads.

网友答案:

Simply replace

data: JSON.stringify({"category_id": id, "category_name": name}),

with

data: {"category_id": id, "category_name": name}
分享给朋友:
您可能感兴趣的文章:
随机阅读: