Akash Deshpande
Akash Deshpande

Reputation: 2645

How to access a Django object in jQuery

I have a Ajax function which gets the Django object from a view.

I want to access all the attributes of the object in jQuery but I am not able to do so.

$.ajax(
{
    url: domain+'/game/android/',                                               
    type:"POST",
    success:function(response){
        response = jQuery.parseJSON(response);                          
        localStorage['userCard'] = response.user_cards_held;
        localStorage['compCard'] = response.comp_cards_held;
        localStorage['game'] = response.game;                               
        alert(response.user_cards_held);// **this shows all the fields. **
        alert(response.user_cards_held.fields);//This does not work. Gives the value as undefined
        window.location = 'file:///android_asset/www/game.html';                        
    },
    error:function(xhr, status, error){
        var err = eval("(" + xhr.responseText + ")");
        alert(err.Message);     

    },

});

View is like this:

    from django.core import serializers
...
json = serializers.serialize('json', objectlists)
return HttpResponse(json, mimetype="application/json")

Object is like this :

[{ "model" : "object.list", "pk" : 1, "fields" : { "name" : "...", ... } }]

I have checked this question :Question Referenced This does not work. What am I doing wrong?

Edit:

To get the field properly I have made the following changes in the success function -

success:function(response){
        response = jQuery.parseJSON(response);                          
        localStorage['userCard'] =jQuery.parseJSON(response.user_cards_held);
        localStorage['compCard'] = jQuery.parseJSON(response.comp_cards_held);
        localStorage['game'] = jQuery.parseJSON(response.game);                               
        alert(jQuery.parseJSON((response.user_cards_held));// **this shows all the fields. **
        alert(jQuery.parseJSON(response.user_cards_held.fields));//This does not work. Gives the value as undefined
        window.location = 'file:///android_asset/www/game.html';                        
    }

Upvotes: 1

Views: 1588

Answers (2)

Juan Carvalho
Juan Carvalho

Reputation: 13

[{ "model" : "object.list", "pk" : 1, "fields" : { "name" : "José", ... } }]

// convert JSON string to JSON Object:<br>
var data = $.parseJSON(response);<br>
// acess name atribute<br>
**data[0].fields.name**;

Upvotes: 0

Bibhas Debnath
Bibhas Debnath

Reputation: 14939

Your response.user_cards_held is an array object -

>> [{ "model" : "object.list", "pk" : 1, "fields" : { "name" : "...", ... } }]
// ^----- Array

So of course response.user_cards_held.fields would be undefined. Your actual object is at response.user_cards_held[0] So you can access the fields attribute like response.user_cards_held[0].fields.

Upvotes: 2

Related Questions