简体   繁体   中英

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.

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.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM