[英]Unable to send json in ajax to django without jquery
I am trying to use AJAX
with Django
but without jQuery
, almost I am successful in doing so but only urlencoded
data can be sent from AJAX to Django and unable to send data in JSON format, but I am able to get a response from Django
to AJAX
in JSON
format too.我正在尝试将
AJAX
与Django
一起使用,但没有jQuery
,几乎我成功地这样做了,但只有urlencoded
数据可以从 AJAX 发送到 Django 并且无法以 JSON 格式发送数据,但我能够从Django
获得响应JSON
格式的AJAX
。
I have tried a lot as you can see comments in these files:我已经尝试了很多,因为您可以在这些文件中看到注释:
senddata.html发送数据.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网址.py
from django.urls import path
from ajaxcontact import views
urlpatterns = [
path('', views.contact, name='contact'),
path('send', views.senddata, name='senddata'),
]
views.py视图.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')
Here, I use @csrf_exempt
to create the POST without the csrf token I am able to send data in urlencoded
but unable to send it in JSON
format在这里,我使用
@csrf_exempt
创建没有 csrf 令牌的 POST 我能够以urlencoded
格式发送数据但无法以JSON
格式发送
Any help will be appreciated任何帮助将不胜感激
your urls should match with request url based on main domain.您的网址应与基于主域的请求网址相匹配。 So change your urls.py file to
因此,将您的 urls.py 文件更改为
path('/contact/send', views.senddata, name='senddata')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.