javascript - Parse ajax response properly - Stack Overflow

I get data from the server with Ajax.Data returned (from firebug):{"users":[{"name"

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?

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?

Share asked Jun 6, 2012 at 11:15 ilyes kooliilyes kooli 12.1k14 gold badges55 silver badges81 bronze badges 1
  • You tried without the eval? (Which is evil and shouldn't be used anyway!) Just data.users[0].name – Richard Dalton Commented Jun 6, 2012 at 11:17
Add a ment  | 

4 Answers 4

Reset to default 10

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);
    });

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744918854a4601004.html

相关推荐

  • javascript - Parse ajax response properly - Stack Overflow

    I get data from the server with Ajax.Data returned (from firebug):{"users":[{"name"

    1天前
    40

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信