将发布数据从angularjs发送到django作为JSON而不是原始内容

Dee*_*eyi 21 python django http-post angularjs

我有这样的请求:

$http({ 
    method: 'POST', 
    url: '/url/', 
    data: 'test=data'
})
Run Code Online (Sandbox Code Playgroud)

在我的django观点中:

class SomeClass(View):
    def get(self, request):
        return HttpResponse("Hello")
    def post(self, request):
        print request.post
        print request.body
        return HttpResponse("Done")
Run Code Online (Sandbox Code Playgroud)

所以,当我这样做时,request.POST 我得到一个空的查询字典:<QueryDict: {}>

但我request.body有:test=data

所以我相信django将数据作为url编码的参数而不是字典接收.

如何以JSON/Dict发送或接收此数据?

mar*_*dev 45

当调用ajax时,你在请求​​体中接收到编码的json字符串,所以你需要使用python的json模块解码它来获取python dict:

json.loads(request.body)
Run Code Online (Sandbox Code Playgroud)

  • 我喜欢这个解决方案,因为我可以使用AngularJS,因为它习惯于使用jQuery而不是黑客攻击它. (5认同)
  • 如果你使用角度4和DRF使用`request.data`. (2认同)

Ser*_*nov 14

在我的情况下工作的东西就像

$http({
    url: '/url/',
    method: "POST",
    data: $.param(params),
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
    }
})
Run Code Online (Sandbox Code Playgroud)

或者更好的变体:

app.config ($httpProvider) ->
    ...
    $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
Run Code Online (Sandbox Code Playgroud)

然后

$scope.save_result = $http.post('/url/', $.param(params))
Run Code Online (Sandbox Code Playgroud)

http://www.daveoncode.com/2013/10/17/how-to-make-angularjs-and-django-play-nice-together/