简体   繁体   中英

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}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM