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

时间:2013-09-24 10:28:51

标签: python django angularjs http-post

我有这样的请求:

$http({ 
    method: 'POST', 
    url: '/url/', 
    data: 'test=data'
})

在我的django观点中:

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

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

但我的request.body有:test=data

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

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

6 个答案:

答案 0 :(得分:45)

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

json.loads(request.body)

答案 1 :(得分:14)

在我的情况下工作类似

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

或者更好的变体:

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

然后

$scope.save_result = $http.post('/url/', $.param(params))

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

答案 2 :(得分:2)

我正在使用zope2,我使用simplejson将请求json解码为python字典:

request_dict = simplejson.loads(request.get('BODY','')

它对我来说正常。通过这种方式,我可以使用angularjs默认的json请求,而不是将其转换为表单post。

答案 3 :(得分:2)

我通过创建装饰器来改进mariodev的解决方案:

$tagtime = $length / $overlaylength;
        $tagtime3 = floor($tagtime);
        $stringtoloop = "' . $tagmp3 . '";
        for ($k = 0 ; $k < $tagtime3; $k++){ $finalstring = +.$stringtoloop; }

现在,每当我创建一个处理# Must decode body of angular's JSON post requests def json_body_decoder(my_func): def inner_func(request, *args, **kwargs): body = request.body.decode("utf-8") request.POST = json.loads(body) return my_func(request, *args, **kwargs) return inner_func @json_body_decoder def request_handler(request): # request.POST is a dictionary containing the decoded body of the request 中的帖子数据的请求处理程序时,我就会添加@json_body_decoder装饰器。

答案 4 :(得分:1)

对于angular 4和Django Rest Framework,使用request.data来获取json对象。

像:

posted_data = request.data

答案 5 :(得分:0)

$http服务需要JS对象,而不是字符串。试试这个:

$http({ 
    method: 'POST', 
    url: '/url/', 
    data: {test: 'data'}
})