Reputation: 577
I'm trying to parse json data in django view. But I got a problem.
I'm using below code snippet.
$(document).ready(function(){
$("#mySelect").change(function(){
selected = $("#mySelect option:selected").text()
$.ajax({
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
url: '/test/jsontest/',
data: {
'fruit': selected,
},
success: function(result) {
document.write(result)
}
});
});
});
when the client side user change the value, ajax code send json data. But server side view receive a data in forms with "fruit=apple". I think it's not json data format. So, I have no idea how to parse the data.
I try to parse like below, But I got 500 Internal server error after calling json.dumps(data)
class JsonRead(View):
template_name = 'MW_Etc/jsonpost.html'
def get(self,request):
return render(request, self.template_name)
def post(self,request):
data = request.body
logger.debug('json data received(%s)' % data)
return HttpResponse(json.dumps(data), content_type='application/json')
Upvotes: 5
Views: 15918
Reputation: 655
Do post JSON string like this.
data: {'data': JSON.stringify({'fruit': selected})}
and receive like
data = json.loads(request.POST.get('data', ''))
Upvotes: 8
Reputation: 611
You need to post the data as JSON string rather than a JavaScript object.
data: JSON.stringify({'fruit': selected})
should do. Also note that you'll then need to json.loads
the data in Django to actually do anything with it.
Upvotes: 6