2017-09-12 2 views
0

Mon grails contrôleur MyController.groovy a l'action suivante:Comment accéder Grails Arraylist d'objets à partir de 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]) 
} 

Cela rend index.gsp avoir accès à myModel par myModelInstance.

En index.gsp, j'ai une méthode javascript comme ci-dessous:

<g:javascript> 
    function someJavascriptFunction(){ 
     var message = $.parseJSON("${myModelInstance.myChildList as grails.converters.JSON}"); 
     console.log("I am from grails: "+message); 
    } 
</g:javascript> 

Considérant que j'ai deux éléments dans la liste, ceci affiche:

I am from grails: [object Object],[object Object] 

Mais ce n'est pas ce que je veux. Comment puis-je accéder aux objets MyChild de la liste et aux propriétés/valeurs de ces objets MyChild dans ma fonction javascript?

Répondre

0

Faites quelques modifications dans votre code Groovy et 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>