简体   繁体   中英

XMLHttpRequest is not sending POST data to Django server

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.

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)

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