问题
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