簡體   English   中英

從 AJAX POST 請求獲取 Django 視圖中的數據

[英]Get data in Django view from AJAX POST request

我是 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)
        }
      })
    }

出於某種原因,我似乎總是為空。 不知道是什么問題

我知道了。 對於不是從 HTML 表單發送的請求,就像我通過 AJAX 調用的情況一樣,只能使用request.body訪問它

感謝這個答案: https : //stackoverflow.com/a/30879038/12806725

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM