正确解析ajax响应

I get data from the server with Ajax.

Data returned (from firebug):

{"users":[{"name":"some name", "age":17},{"name":"some name2", "age":25}]}

When I try

$.post('server.php', function(data){
    var users = eval(data).users;
    alert(users[0].name);
});

I get on firebug:

Uncaught SyntaxError: Unexpected token )

Any help?

You have to surround the json string with brackets

$.post('server.php', function(data){
    var users = eval('('+data+')').users;
    alert(users[0].name);
});

DEMO

I don't get the point on eval() but maybe I don't know the function well...

With this works:

var data = {"users":[{"name":"some name", "age":17},{"name":"some name2", "age":25}]};
alert(data.users[0].name);

​You also may loop with:

$.each(data.users, function (i, user_obj){
    alert(user_obj.name);
});

Take a look at this demo.

It's better to add the dataType: "json" to your ajax request so it's properly parsed.

Please do not use eval - it's evil

Instead, simply use a parameter of "json".

$.post('server.php', function(data) {
    alert(data.users[0].name);
}, "json");

If your headers are proper, you don't even need the json parameter, but it forces jQuery to want to receive and parse it as JSON.

encode data in brackets with single quotes

 $.post('server.php', function(data){
        var users = eval('('+data+')');
        alert(users[0].name);
    });