代码之家  ›  专栏  ›  技术社区  ›  Ghasem

在django中读取Ajax post数据

  •  0
  • Ghasem  · 技术社区  · 7 年前

    promise 在我的django项目中:

    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
    

    我在读取post数据时是否遗漏了什么,或者我的ajax请求有什么问题?

    2 回复  |  直到 7 年前
        1
  •  3
  •   ruddra    7 年前

    我想你可以这样试试:

    import json
    
    @csrf_exempt
    def get_blogs(request):
        cat_id = json.loads(request.body).get('path')
        print("RESULT: " + str(cat_id))
    
        2
  •  1
  •   Community Mohan Dere    6 年前

    Django documentation

    HttpRequest.POST

    包含所有给定HTTP POST参数的类似字典的对象, 假设请求包含表单数据。请参阅QueryDict 文件如下。如果您需要访问发布的原始或非表单数据 在请求中,通过HttpRequest.body属性访问它

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