简体   繁体   中英

AJAX call to Django View returns None to data

I have been trying to get data that I send using AJAX with a Django view. I have this AJAX call

$.ajax({
    method: "POST",
    url: "{% url 'change_publish_status' %}",
    value: {"company_id": company_id, "published": published},
    dataType: 'json',
    headers: {"X-CSRFToken": '{{ csrf_token }}'}
});

and I'd like to access the company_id and the published variables from the django view. I have tried many things

  • self.request.POST.get('company_id') --> returns None
  • self.request.POST.get('company_id', None) --> returns None
  • self.request.body --> returns b''

This is my view right now

@method_decorator(login_required, name='dispatch')
class ChangePublishStatus(TemplateView):
    def post(self, *args, **kwargs):
        company_id = self.request.POST.get('company_id', None)
        published_status = self.request.POST.get('published') == "true"

        print(company_id)

        return JsonResponse({"status": "ok"})

    def get(self, *args, **kwargs):
        return redirect("list")

To send the data in the POST call, pass the data in the data argument rather than value .

$.ajax({
    method: "POST",
    url: "{% url 'change_publish_status' %}",
    data: {"company_id": company_id, "published": published},
    dataType: 'json',
    headers: {"X-CSRFToken": '{{ csrf_token }}'}
});

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