我有这个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将我的用户对象视为数组呢?
答案 0 :(得分:1)
您应该将响应作为JSON对象发送(来自grails.converters包)
def getUsers = {
def users = Lists.asList("user1", "user2", "user3")
render users as JSON;
}