如何在javascript中迭代grails列表

时间:2016-05-22 19:19:10

标签: javascript grails

我有这个grails控制器,它返回一个字符串列表:

class UserController {
  def getUsers = {
    def users = Lists.asList("user1", "user2", "user3")
    render users : users;
  }
}

调用上述控制器的javascript:

    var displayUsers = function(users) {
       for (var i = 0; i < users.length; i++) {
          console.log(users[i];
// this iterates over each character in the users object and not over                 
// it's elements
// users objects is interpreted as a string object and not as a list
       }
    }

$(document).ready(function(){
    $('.expand-group').on('click', function(e) {
        $.ajax({
            url: '/getUsers',
            type: "GET",
            data: {}
        }).done(function(data, textStatus) {
               displayUsers(data);
        });
    });
});

我的输出如下:

[
'
u
s
e
r
s
'
:
[
'
u
...

那么如何告诉javascript将我的用户对象视为数组呢?

1 个答案:

答案 0 :(得分:1)

您应该将响应作为JSON对象发送(来自grails.converters包)

def getUsers = {
    def users = Lists.asList("user1", "user2", "user3")
    render users as JSON;
}