Reputation: 14144
There is a client-side JavaScript and server-side Python, powered by Django. There is a data object: foo_data = {"foo":1, "bar":2}
.
Now, I would like to send a post-request using dojo/request/xhr
, and send foo_data
along with another variable:
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);
});
And then read sent data in Django's views.py
file:
def post(self, request, *args, **kwargs):
json.loads(request.body)
BUT, it doesn't work:
foo_data
, python doesn't recognize it correctly as JSON object and can't read it using json.loads
.foo_data
using JSON.parse
because it is already an object!request.POST
is an empty QueryDict
request.body
has string word object
(instead of the real object)Any ideas how to solve this?
Goal: send JSON object from JS --> Python and read it on server-side.
Upvotes: 1
Views: 1298
Reputation: 73918
dojo.xhr has been deprecated, please consider using dojo/request
more info here:
https://dojotoolkit.org/reference-guide/1.10/dojo/request/xhr.html#dojo-request-xhr
For a live example of post to a server, you can look source code for this page: https://dojotoolkit.org/documentation/tutorials/1.8/ajax/demo/dojo-request-xhr-post.php
Here some a simple example of usage:
require(dojo/request"],
function(request){
// post the data to the server
request.post("your/server/script", {
// send your data here
data: { yourData: 1},
// wait 2 seconds for a response
timeout: 2000
}).then(function(response){
// do smt here when operation is successfully executed
});
}
);
Regarding your code sample in your question, you have't posted your server side code. But you could try to pass your data to the server using JSON.stringify()
.
Upvotes: 2