2017-09-12 14 views
0

grails控制器MyController.groovy访问Grails的ArrayList对象的有下列行为:如何从JavaScript

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

这使得通过myModelInstance有机会获得myModelindex.gsp

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对象内的属性/值?

回答

0

在你的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>