首页 > 解决方案 > 在 django 中读取 Ajax 发布数据

问题描述

我在 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 请求有问题?

标签: pythonajaxdjangoes6-promise

解决方案


我想你可以这样尝试:

import json

@csrf_exempt
def get_blogs(request):
    cat_id = json.loads(request.body).get('path')
    print("RESULT: " + str(cat_id))

推荐阅读