【问题标题】:Unable to send json in ajax to django without jquery无法在没有 jquery 的情况下将 ajax 中的 json 发送到 django
【发布时间】:2021-09-26 07:08:59
【问题描述】:

我正在尝试将AJAXDjango 一起使用,但没有jQuery,我几乎成功地这样做了,但只有urlencoded 数据可以从AJAX 发送到Django,并且无法以JSON 格式发送数据,但我也能得到DjangoAJAXJSON 格式的回复。

我已经尝试了很多,因为您可以在这些文件中看到 cmets:

发送数据.html

<!doctype html>
<html lang="en">

<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

    <title>Send AJAX data</title>
</head>

<body>
    <h2>Send AJAX data by using the button</h2>
    <button id="btn-submit" class="btn btn-outline-dark">SEND</button>


    <script>
        var sendbtn = document.getElementById('btn-submit')
        sendbtn.addEventListener('click', sendBtnHandler)

        function sendBtnHandler() {
            console.log('sendBtn is clicked')

            const xhr = new XMLHttpRequest()

            xhr.open('POST', 'http://localhost:8000/contact/send', true)
            // xhr.getResponseHeader("Content-type", "application/json");
            // xhr.getResponseHeader("Content-type", "application/x-www-form-urlencoded");
            // xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            // xhr.setRequestHeader("Content-type", "application/json");
            xhr.setRequestHeader("Content-type", "application/json;charset=UTF-8");


            xhr.onprogress = function () {
                console.log("on progress, wait a while until data is fetched")
            }

            xhr.onload = function () {
                console.log('success')
                console.log(this.responseText)
            }

            let params = `{"name":"mayur90","salary":"12213","age":"23"}`
            let b = 2
            let d = 4 
            // let params = `a=${b}&c=${d}`
            xhr.send(params)
            // xhr.send(b)
            console.log(params)

        }
    </script>





    <!-- Optional JavaScript; choose one of the two! -->

    <!-- Option 1: Bootstrap Bundle with Popper -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"
        integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"
        crossorigin="anonymous"></script>

    <!-- Option 2: Separate Popper and Bootstrap JS -->
    <!--
    <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js" integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i+tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.min.js" integrity="sha384-cVKIPhGWiC2Al4u+LWgxfKTRIcfu0JTxR+EQDz/bgldoEyl4H0zUF0QKbrJ0EcQF" crossorigin="anonymous"></script>
    -->
</body>

</html>

urls.py

from django.urls import path
from ajaxcontact import views

urlpatterns = [
    path('', views.contact, name='contact'),
    path('send', views.senddata, name='senddata'),
]

views.py

from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt

# Create your views here.

@csrf_exempt
def senddata(request):
    print(request.method)
    # print(request.GET)
    print('POST requests are', request.POST)
    print(request.POST.get('name'))
    if request.method == 'POST':
        return JsonResponse('{"name":"a"}', safe=False)
    return render(request, 'senddata.html')

在这里,我使用 @csrf_exempt 创建没有 csrf 令牌的 POST 我能够以urlencoded 发送数据,但无法以JSON 格式发送数据

任何帮助将不胜感激

【问题讨论】:

标签: javascript html jquery django ajax


【解决方案1】:

您的网址应与基于主域的请求网址匹配。因此,将您的 urls.py 文件更改为
path('/contact/send', views.senddata, name='senddata')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-14
    • 2015-11-06
    • 2014-09-22
    • 1970-01-01
    • 1970-01-01
    • 2017-09-15
    • 2015-01-03
    • 2021-09-20
    相关资源
    最近更新 更多