sending data from angularjs to django

2019-02-17 16:57发布

I am sending a POST AJAX request using Angularjs and its $http module to Django server. Here is an example:

$http({ 
        method: 'POST', 
        url: '/url/', 
        data: 'test data'
  }).
  success(function(data, status, headers, config) {
        doSomeStuffWhenSuccess();
  });

The problem is what I get in Django. No matter what I send the data is always the key of QueryDict object and value of that is always an empty list.

<QueryDict: {u'test data': [u'']}>

I don't have a clue why. What am I missing?

I use almost default created Django application with default middlewares only. I created only a view and set an url in url config. Version of Django is 1.3. And I configured angular's $http module to always send a header containg csrf token to satisfy Django.

2条回答
甜甜的少女心
2楼-- · 2019-02-17 17:52

I resolved this with jQuery param function. I think it's more elegant solution.

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

Now it works like I wanted.

查看更多
不美不萌又怎样
3楼-- · 2019-02-17 17:56

I believe django thinks you are sending a urlencoded form, ex. key=value&key2=value2...

if you'd try:

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

You should get

<QueryDict: {u'test': [u'data']}>

You can always obtain the data (raw body content) as follows:

request.body

Hope this is what you are looking for.

查看更多
登录 后发表回答