【问题标题】:Get data in Django view from AJAX POST request从 AJAX POST 请求中获取 Django 视图中的数据
【发布时间】:2020-05-19 08:05:12
【问题描述】:

我是 Django 新手,正在从事一个不涉及在 Django 中使用表单的项目。我有一个 JS,它对我的​​后端 Django Web 服务进行 AJAX POST 调用,我只想得到它的响应。 但是,我这样做总是一无所获。我进行了很多搜索,但找不到解决方案。这是我的代码:

我的项目urls.py

from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path('home/', include('demo_app.urls')),
    path('admin/', admin.site.urls),
]

我的应用urls.py

from django.urls import path

from . import views

urlpatterns = [
    path('', views.index, name='index'),
    path('dispatcher/', views.dispatcher, name='dispatcher'),
]

我的views.py

from django.shortcuts import render
from django.http import HttpResponse
from demo_app.models import VesselStatus
from django.db.models import Count
from django.views.decorators.csrf import csrf_exempt

def index(request):
    return HttpResponse("Hello world")

@csrf_exempt
def dispatcher(request):
    if request.method == "POST":
        print(request.POST.get("inputText"))
        return HttpResponse(request)

我不想使用表单,因此 CSRF 豁免装饰器

我的 AJAX 调用:

if(individual_result.toLowerCase().includes('some text'))
    {
      console.log("Found");
      data = {
        "inputText": individual_result
      }
      $.ajax
      ({
        crossDomain: true,
        type: "POST",
        contentType: "application/json",
        url:"--address-of-local--/home/dispatcher/",
        data: JSON.stringify(data),
        dataType: 'json',
        cache: false,
        success: function(response){
          console.log(response)
        }
      })
    }

出于某种原因,我似乎总是为空。不知道是什么问题

【问题讨论】:

  • 您是否尝试打印request.POST?您在浏览器的开发者工具中看到请求正文的样子了吗?
  • @schillingt 我得到一个空字典 :(

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


【解决方案1】:

我明白了。对于不是从 HTML 表单发送的请求,就像我通过 AJAX 调用的情况一样,它必须使用 request.body ONLY 访问它

感谢这个答案:https://stackoverflow.com/a/30879038/12806725

【讨论】:

    猜你喜欢
    • 2011-12-20
    • 2016-03-09
    • 2020-03-15
    • 2013-12-20
    • 1970-01-01
    • 1970-01-01
    • 2012-07-05
    • 1970-01-01
    • 2019-11-26
    相关资源
    最近更新 更多