javascript - 如何从JavaScript访问Grails对象的Arraylist

标签 javascript grails groovy

我的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/

相关文章:

javascript - 如何通过 Javascript 查明是否安装了 Adob​​e Flash 播放器?

javascript - 如何使用 jquery 在调用函数中传递函数的变量?

arrays - 具有嵌入式数组的JSON对象保存在Controller中

jenkins - 如何打印多行字符串参数的每个元素?

java - 如何更改 Groovy 的 JavaDoc 语法颜色

javascript - 带 for 循环的嵌套 Promise 不起作用

javascript - jquery datepicker 不适用于动态创建的 html

grails - 具有相同标识符的不同对象

json - 如何将默认Grails标记库导入JSON View

grails - 如何在Grails remoteFunction中将参数从gsp传递到 Controller 作为参数的一部分