javascript - Sending a POST request through Javascript on Django - failed to retrieve data
问题描述
I'm trying to send a POST request to my Django view using plain javascript (I don't want any unnecessary libraries involved). The data is not sent through a form, but by using fetch
. For now I just want to be able to manipulate the request.POST
in my views.py, nothing more.
Here's my code:
Javascript
let article = document.querySelector('article')
articleId = article.getAttribute('data-product-id')
# some other stuff
fetch("{% url 'shop:shoplist' 1 %}", {
method: 'POST',
dataType: "application/json",
data: {'article_id': articleId},
headers: {'X-CSRFToken': csrf_token}
})
Python
if request.method == 'POST':
testing = request.POST
return JsonResponse({'test': testing})
The request is sent, the csrftoken
is received correctly, but the request.POST
returns just <QueryDict: {}>
, instead of what I'm expecting (headers, data...).
I've searched and found a lot of similar questions, the most similar one being this one, but still I can't seem to find a solution.
Any idea?
解决方案
尝试将“内容类型”添加到fetch
调用中的标头(而不是 dataType 参数),并将数据参数更改为带有字符串化对象的正文:
fetch("{% url 'shop:shoplist' 1 %}", {
method: 'POST',
body: JSON.stringify({'article_id': articleId}),
headers: {
'X-CSRFToken': csrf_token,
'Content-Type': 'application/json'
}})
推荐阅读
- ruby - 在 Ruby 结构中正确定义常量
- sql - Oracle - 根据最新日期选择记录
- javascript - JavaScript 三元运算符:document.body.className = document.body.className != "cls" ? “cls”:“”;?
- android - 使用 dagger android 时如何在通知上创建 viewmodel 的实例
- kml - 工作多年的 KML/KMZ 文件不再工作
- javascript - 您可以使用phonegap中的缓存来保存图像或访问android中的文件夹吗?
- css - 试图获取 section.class1 而不是 section.class1, scss
- html - 当表格垂直扩展至其最大高度时 - 使元素在下一个表格单元格列中弹出
- sql-server - 无法使用 SQL Server 数据库访问 Cloud SQL 上的导入数据
- php - phpoffice/电子表格如何在图表中为每一列添加一个值