Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to parse json data with ajax POST in Django view

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')
like image 539
eachone Avatar asked Dec 15 '22 12:12

eachone


1 Answers

Do post JSON string like this.

data: {'data': JSON.stringify({'fruit': selected})}

and receive like

data = json.loads(request.POST.get('data', ''))

like image 101
fakhir hanif Avatar answered Jan 12 '23 12:01

fakhir hanif