我的grails
Controller MyController.groovy
具有以下操作:
def index = {
def myModel = new MyModel()
// res below is a list of MyChild objects from a service call
def childList = jacksonObjectMapper.readValue(res, new TypeReference<List<MyChild>>() {})
myModel.setMyChildList(childList)
render(view: 'index', model: [myModelInstance: myModel])
}
这使
index.gsp
可以通过myModel
访问myModelInstance
。在
index.gsp
中,我有一个javascript
方法,如下所示:<g:javascript>
function someJavascriptFunction(){
var message = $.parseJSON("${myModelInstance.myChildList as grails.converters.JSON}");
console.log("I am from grails: "+message);
}
</g:javascript>
考虑到列表中有两个元素,将输出:
I am from grails: [object Object],[object Object]
但这不是我想要的。如何访问列表中的
MyChild
对象以及javascript函数中这些MyChild
对象中的属性/值?
最佳答案
在Groovy和JS代码中进行一些修改。
def index = {
def myModel = new MyModel()
// res below is a list of MyChild objects from a service call
def childList = jacksonObjectMapper.readValue(res, new TypeReference<List<MyChild>>() {})
myModel.setMyChildList(childList)
render(view: 'index', model: [myModelInstance: myModel grails.converters.JSON])
}
在JavaScript中
// Get model rendered from groovy action.
var myModelInstance = ${myModelInstance};
//Now iterate over the json object to get values
for(var i = 0 ; i < myModelInstance.length; i++){
console.log(myModelInstance[i]);
/*If the list contain nested object (groovy map inside the list)
then get key and values as,*/
console.log("key:",myModelInstance[i].keyName);
console.log("value:",myModelInstance[i].valueName);
}
</script>
关于javascript - 如何从JavaScript访问Grails对象的Arraylist,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46172438/