我在Django项目中使用promise收到了Ajax请求:
var path = window.location.pathname;
fetch('/getblogs/', {
method: 'post',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json'
},
body: JSON.stringify({'path': path})
}).then(function (response) {
return response.json();
});
该请求位于js
文件中,没有任何形式。
我正在尝试像这样读取views.py
中的数据:
@csrf_exempt
def get_blogs(request):
cat_id = request.POST.get('path')
print("RESULT: " + str(cat_id))
但是在输出中我得到:
RESULT: None
我在阅读帖子数据时是否缺少某些东西,或者我的ajax请求有问题吗?
答案 0 :(得分:1)
我认为您可以尝试这样:
import json
@csrf_exempt
def get_blogs(request):
cat_id = json.loads(request.body).get('path')
print("RESULT: " + str(cat_id))
答案 1 :(得分:1)
HttpRequest.POST
类似于字典的对象,包含所有给定的HTTP POST参数, 前提是该请求包含表单数据。参见QueryDict 下面的文档。如果您需要访问发布的原始或非格式数据 在请求中,通过HttpRequest.body属性访问它 代替。
尝试使用json.loads(request.body)['path']