user1666450
user1666450

Reputation: 59

Can I define a javascript variable to a grails object?

Can I assign a javascript variable to a grails object like this?

var newReport = ${report};

report is a grails domain object, which is passed back from controller to the gsp file.

Currently this doesn't work in my page.

Upvotes: 0

Views: 1737

Answers (2)

coderLMN
coderLMN

Reputation: 3076

Just render domain object as JSON to gsp, where some javascript code get the json by eval() function. For instance:

domain class - Band:

String bandName    //some property
...

controller:

def bands = Band.list()
render(template:"result", model:[bands:bands as JSON]

_result.gsp:

<script>
    var bandList = eval(${bands});
    for(i=0; i<bandList.length; i++){   
        var name = bandList[i].bandName;
        ....
    }
    ....
</script>

Upvotes: 0

user800014
user800014

Reputation:

Assuming that report is a Grails domain class, you will have to 'translate' this to a valid javascript format. One way is to set this as JSON. Something like:

In the controller

def reportJson = report as JSON

In the gsp

<script type='text/javascript'>
  var newReport = $.parseJSON("${reportJson}");
</script>

The parseJSON takes the json string and return a javascript object.

Upvotes: 2

Related Questions