[英]Can I define a javascript variable to a grails object?
Can I assign a javascript variable to a grails object like this? 我可以将javascript变量分配给这样的grails对象吗?
var newReport = ${report};
report
is a grails domain object, which is passed back from controller to the gsp file. report
是一个grails域对象,它从控制器传递回gsp文件。
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. 假设该报告是Grails域类,您必须将其“翻译”为有效的javascript格式。 One way is to set this as JSON. 一种方法是将其设置为JSON。 Something like: 就像是:
In the controller 在控制器中
def reportJson = report as JSON
In the gsp 在gsp中
<script type='text/javascript'>
var newReport = $.parseJSON("${reportJson}");
</script>
The parseJSON takes the json string and return a javascript object. parseJSON接受json字符串并返回一个javascript对象。
Just render domain object as JSON to gsp, where some javascript code get the json by eval() function. 只需将域对象作为JSON呈现给gsp,其中一些javascript代码通过eval()函数获取json。 For instance: 例如:
domain class - Band: 域类 - 乐队:
String bandName //some property
...
controller: 控制器:
def bands = Band.list()
render(template:"result", model:[bands:bands as JSON]
_result.gsp: _result.gsp:
<script>
var bandList = eval(${bands});
for(i=0; i<bandList.length; i++){
var name = bandList[i].bandName;
....
}
....
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.