1

My view looks like this:

def change(request):
    users = Account.objects.all().to_json()
    return HttpResponse(users, mimetype='application/json')

And my javascript in my template looks like this:

$( "#btn" ).click(function() {

  jQuery.ajax({
    url: '/change/',
    type: 'get', 
    dataType: 'json',
    success: function(data) {

      alert(data.username)
    },
    failure: function(data) { 
        alert('Got an error dude');
    }
  }); 

I can see in the firebug console that server's response looks ok:

[{"username": "admin", "project_list": [], "password": "pbkdf2_sha256$10000$OA1nceoBeMj2$XFZfZdfOpd7LKOGKyHrnVPUv89daY8+RzoAhApI+ePs=", "is_active": true, "is_superuser": true, "is_staff": false, "last_login": {"$date": 1420983256456}, "_cls": "User.Account", "groups": [], "user_permissions": [], "role": "admin", "_id": {"$oid": "54b27bca8a8d5114ee764bd7"}, "date_joined": {"$date": 1420983242745}}]

But when i try to print anything in alert using

alert(data)

or

alert(data.field) 

for example field = username i get undefined. When i use alert(data) it just says it's an object.

Any suggestions?

1 Answer 1

1

use $.each() iterator:

$.each(data, function(i, item){
    console.log(item.username);
});

Because you get an [{}, {}] array of js objects, so if you directly access the key name to get the respective value you can't get it. so instead you have to loop in it to have the access to the objects.

So in the code above item is the current js object and item.username will log admin.

Sign up to request clarification or add additional context in comments.

1 Comment

It works fine with the $.each iterator. Thanks! Are there no other options?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.