jmitchel3
jmitchel3

Reputation: 391

Clean up Django Ajax JSON GET Request

So I'm trying to use AJAX to load some data. I can get the data to load but it's stuck in json. How do I make it so it's cleaner & more human readable?

//jquery
$.get("/get_artwork", function(data) {
         var obj = jQuery.parseJSON(data)
         $('.result').append("<br/> " + data + " ");
     });

#Views.py 
def get_artwork(request):
    if request.is_ajax():
    artwork = Artwork.objects.all()[1:]
    if request.method == 'GET':
        data = serializers.serialize("json", artwork, fields=('name','updated'),  indent=2, use_natural_keys=True)
        return HttpResponse(data,mimetype='application/javascript')
    elif request.method == 'POST':
            message = "This is an XHR POST request"
            # Here we can access the POST data
            print request.POST
    else:
        message = "Hello"
return HttpResponse(message) 

and this is what renders:

[ { "pk": 3, "model": "artworks.artwork", "fields": { "updated": "2013-01-20T06:46:24Z" } }, { "pk": 2, "model": "artworks.artwork", "fields": { "updated": "2013-01-17T23:44:26Z" } }, { "pk": 1, "model": "artworks.artwork", "fields": { "updated": "2013-01-17T23:43:22Z" } } ]

How would I make this more human-readable? Thanks!

Upvotes: 0

Views: 985

Answers (1)

Byron Ruth
Byron Ruth

Reputation: 987

Based on the comments you've left.. it seems your issue is downstream in the client (e.g. web browser). It is not clear what you mean by stuck in JSON. If you are using JavaScript to parse the JSON, you will need to use JSON.parse() to turn it into a native JavaScript object. If you are using jQuery and the $.ajax() method, you will need to set the mimetype to application/json for it to automatically parse it as JSON.

UPDATE

If you want to control how the JSON data is rendered in the browser, I suggest you parse the JSON response into a native JavaScript object and then iterate over objects and fields you want to render in the page. As an example, using jQuery:

$.ajax({
    url: '/some-url/',
    dataType: 'json',
    success: function(resp) {
        var i, k, li, obj, fields;

        for (i = 0; i < resp.length; i++) {
            obj = resp[i];
            // render obj pk or model name here... now iterate over fields
            fields = obj.fields;

            for (k of obj.fields) {
                li = $('<li>').text(k + ': ' + obj.fields[k]);
                // append the li to some element..
            }
        }
    }
});

Upvotes: 1

Related Questions