最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - XMLHttpRequest is not sending POST data to Django server - Stack Overflow

programmeradmin3浏览0评论

Javascript to send data via XMLHttpRequest

csrftoken = getCookie('csrftoken'); 
var request = new XMLHttpRequest();
request.open('POST', '/register');
request.setRequestHeader("X-CSRFToken", csrftoken); 
request.setRequestHeader("Content-Type", "text/plain;charset=UTF-8"); 
request.send("data");

Django view:

def register_user(request):
    if request.method == "POST":

        print("django server")
        print(request.POST)

Sever is printing:

django server
<QueryDict: {}>

I have also triend application/json as content type with json data, but that is also not working. The data does not seem to be being passed to the server. Not sure why.

Javascript to send data via XMLHttpRequest

csrftoken = getCookie('csrftoken'); 
var request = new XMLHttpRequest();
request.open('POST', '/register');
request.setRequestHeader("X-CSRFToken", csrftoken); 
request.setRequestHeader("Content-Type", "text/plain;charset=UTF-8"); 
request.send("data");

Django view:

def register_user(request):
    if request.method == "POST":

        print("django server")
        print(request.POST)

Sever is printing:

django server
<QueryDict: {}>

I have also triend application/json as content type with json data, but that is also not working. The data does not seem to be being passed to the server. Not sure why.

Share Improve this question edited Dec 20, 2019 at 16:43 Shahid Manzoor Bhat 1,3351 gold badge15 silver badges32 bronze badges asked Dec 20, 2019 at 16:37 Arthur ChoateArthur Choate 5336 silver badges21 bronze badges 2
  • Can you show your urls.py file? – funnydman Commented Dec 21, 2019 at 11:07
  • @funnydman I eventually figured this out. Posting answer now if you're curious. – Arthur Choate Commented Dec 26, 2019 at 14:58
Add a ment  | 

2 Answers 2

Reset to default 9

The request actually was being sent. This is how to access data:

def register_user(request):
    if request.method == "POST":
        print(request.body) # this would print "data"

In order for print(request.POST) to work the Content-Type must be 'application/x-www-form-urlencoded'

Try this it works for me

from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse

@csrf_exempt
def register_user(request):
    if request.is_ajax():
        status = "1"
    else:
        status = "0"
    return HttpResponse(status)
发布评论

评论列表(0)

  1. 暂无评论