Django post data from Javascript function

狂风中的少年 提交于 2019-12-25 02:27:31

问题


I'm trying to send a string to a post view via checkbox being checked and unchecked. The part I am having trouble with is on the post view being able to get read the data.

I have the name being generated during the templating of the HTML to tell me the id of the item. Then the javascript is supposed to pass the name of the checkbox to the post view and then just print out the post value.

Error

The error I'm getting is that it returned a "None" so I'm thinking I'm not getting the name right.

In the data field of the javascript, I also tried "data:{data:$header}" and I got the same result.

Javascript

$("input[type='checkbox']").change(function() {

      // console.log($header = $(this)[0].name)
      $header = $(this)[0].name

      $.post({
            url: "",
            data: $header,
            headers: {
                'X-CSRFToken': csrftoken
            }
        })

          });

Django view.py

class CurrentCodeView(LoginRequiredMixin,DetailView):
    template_name = 'codes/currentCodes.html'
    def get(self, request, *args, **kwargs):
     //doing alot of stuff

    def post(self,request,*args, **kwargs):
        print(request.POST.get('data'))

回答1:


OK. You're not assigning a return value, and print doesn't return anything to the client. This will return a response to the client:

from django.http import JsonResponse

def post(self, request, *args, **kwargs):
    some_text = 'A reply'
    return JsonResponse({'some_text': some_text})


来源:https://stackoverflow.com/questions/52485191/django-post-data-from-javascript-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!