【问题标题】:XMLHttpRequest is not sending POST data to Django serverXMLHttpRequest 没有向 Django 服务器发送 POST 数据
【发布时间】:2020-04-13 03:59:30
【问题描述】:

Javascript 通过 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 视图:

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

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

服务器正在打印:

django server
<QueryDict: {}>

我也将 application/json 作为带有 json 数据的内容类型,但这也不起作用。数据似乎没有被传递到服务器。不知道为什么。

【问题讨论】:

  • 你能出示你的urls.py文件吗?
  • @funnydman 我最终想通了。如果您好奇,请立即发布答案。

标签: javascript django python-3.x django-views


【解决方案1】:

请求实际上正在发送。这是访问数据的方法:

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

为了让 print(request.POST) 工作,Content-Type 必须是 'application/x-www-form-urlencoded'

【讨论】:

    【解决方案2】:

    试试这个对我有用

    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)
    

    【讨论】:

    • 问题是请求没有发送任何参数。但是,它正在发出成功的请求。
    猜你喜欢
    • 1970-01-01
    • 2015-03-11
    • 2016-04-05
    • 2017-12-28
    • 2018-11-18
    • 1970-01-01
    • 2020-02-01
    • 2013-06-09
    • 1970-01-01
    相关资源
    最近更新 更多