0

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.

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Could also do $.parseJSON("${report as JSON}"); if you didn't want to update the controller.
0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.