【发布时间】:2020-10-28 16:45:31
【问题描述】:
我有一个 JS 事件触发函数,其目标是发送一个 POST 请求以更新我数据库中的一些对象。触发该函数的事件是一个drop-event,所以我最初避免使用表单来传递我的请求,但如果我做错了请告诉我。
大编辑:
我发现我的错误是我的帖子请求中没有包含 csrf_token。
但是,我仍然有一个错误:当我在 django 视图上执行 print(request.POST) 时,我的帖子请求为空。
我的 JS 文件:
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i].trim();
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
var csrftoken = getCookie('csrftoken');
const dragDrop = function (e) {
e.preventDefault()
const droppedElId = e.dataTransfer.getData('Text/html').split('__id-')[1]
const request = new XMLHttpRequest()
request.open('POST', '', true)
request.setRequestHeader('X-CSRFToken', csrftoken)
request.setRequestHeader('Content-Type', 'application/json')
// request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8')
request.send(JSON.stringify({
"request_name":"change-extra-fields",
"type":"increase",
"id":droppedElId,
}))
}
当我这样做时,request.POST 的查询字典为空。但是,如果我将Content-Type 标头更改为application/x-www-form-urlencoded,则请求有效,但它将所有内容放在同一个键上。
例子:
“应用程序/json”的结果:
<QueryDict: {}>
'application/x-www-form-urlencoded' 的结果:
<QueryDict: {'{"request_name":"change-extra-fields","type":"increase","id":"8"}': ['']}>
无论如何,我认为“应用程序/json”应该可以正常工作,但我不知道为什么不正常..
【问题讨论】:
标签: javascript django