I am trying to convert an AJAX request retrieving JSON from JS to Python's dictionary in Django, but unsuccessfully. Please help.
This is the original JS code:
myJSON = JSON.stringify(myJsObject);
// POST - send JSON data to Python/Django server
$.ajax({
url: "/savemyexposuresituation",
type: "POST",
datatype: 'json',
data: myJSON,
async: false,
success: function() {
alert('Your data is saved :)');
},
error: function() {
alert('Error occured :(');
}
});
}
This is the Django side:
def saveExposureSituation(request):
#get es data - JSON file
fromJs = request.POST
fromJs = json.loads(fromJs)
All I get is JSON object must be string, not QueryDict
. I tried to convert this QueryDict to something else unsuccessfully.
request.POST
is for form-encoded data. You should be using request.body
.
In python 3 to convert byte to strings you need to use decode("utf-8")
. So may be to something like this request.POST.decode("utf-8")
Thanks to responses, the complete answer would be:
def saveExposureSituation(request):
fromJs = request.body
fromJs = fromJs.encode('utf-8')
#now we can load our JSON from JS
fromJs = json.loads(fromJs)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.