Send JSON object via POST from JavaScript to Python
<p>There is a client-side JavaScript and server-side Python, powered by Django. There is a data object: <code>foo_data = {"foo":1, "bar":2}</code>.</p>

<p>Now, I would like to send a post-request using <code>dojo/request/xhr</code>, and send <code>foo_data</code> along with another variable:</p>

<pre><code>xhr.post(document.location.href, {
    data: {
        'is_foo': true,
        'data': foo_data
    },
    headers: { 'Content-Type': 'application/json' }
}).then(function(text){
    console.log('The server returned: ', text);
});
</code></pre>

<p>And then read sent data in Django's <code>views.py</code> file:</p>

<pre><code>def post(self, request, *args, **kwargs):
    json.loads(request.body)
</code></pre>

<p>BUT, it doesn't work:</p>

<ul>
<li>if I ssend <code>foo_data</code>, python doesn't recognize it correctly as JSON object and can't read it using <code>json.loads</code>.</li>
<li>I can't encode <code>foo_data</code> using <code>JSON.parse</code> because it is already an object!</li>
<li><code>request.POST</code> is an empty <code>QueryDict</code></li>
<li><code>request.body</code> has string word <code>object</code> (instead of the real object)</li>
</ul>

<p>Any ideas how to solve this?</p>

<p>Goal: send JSON object from JS --> Python and read it on server-side.</p>