【问题标题】:Read Ajax post data in django在 django 中读取 Ajax 发布数据
【发布时间】:2018-11-19 08:30:56
【问题描述】:

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

【问题讨论】:

    标签: python ajax django es6-promise


    【解决方案1】:

    我认为你可以这样尝试:

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

    【讨论】:

    • 我应该去找正文而不是帖子。这解决了这个问题。谢谢!
    【解决方案2】:

    来自Django documentation

    HttpRequest.POST

    一个类似字典的对象,包含所有给定的 HTTP POST 参数, 前提是请求包含表单数据。请参阅查询字典 下面的文档。如果您需要访问发布的原始或非表单数据 在请求中,通过 HttpRequest.body 属性访问它 而是。

    尝试使用json.loads(request.body)['path']

    【讨论】:

      猜你喜欢
      • 2012-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-29
      • 2019-03-29
      • 2015-11-25
      相关资源
      最近更新 更多