[英]How to pass or use variable from GSP in Javascript
I have below line in my grails gsp file. 我的grails gsp文件中有下面一行。
<div class="pagination">
<g:paginate total="${lotCount ?: 0}" />
</div>
I want to pass lotCount value to one of my javascript named area-switcher.js file to further use it. 我想将lotCount值传递给我的一个名为area-switcher.js的javascript文件之一,以进一步使用它。 How can I do this? 我怎样才能做到这一点?
I tried to refer one suggestion from How to pass a value directly from a controller to a javascript file in Grails where I do below in my gsp 我试图从如何将值直接从控制器传递到Grails中的javascript文件中的一个建议,在我的gsp中进行以下操作
<g:javascript> var theId = ${lotCount} </g:javascript>
and try below in my js file for testing 然后尝试在我的js文件中进行测试
alert(theId);
but it doesn't work. 但这不起作用。 Got error like ReferenceError: theId is not defined. 出现类似ReferenceError的错误:未定义theId。 Please help. 请帮忙。
Use a hiddenField: 使用hiddenField:
<g:hiddenField name="lotCount" value="${lotCount}" />
<div class="pagination">
<g:paginate total="${lotCount ?: 0}" />
</div>
Your solution should work. 您的解决方案应该可以工作。
Just ensure that in source of generated html page line 只要确保在生成的html页面行的源中
<g:javascript> var theId = ${lotCount} </g:javascript>
is placed before line which includes area-switcher.js 放在包含area-switcher.js的行之前
<script type="text/javascript" src="area-switcher.js">
Besides that, there are two more options to pass some value from .gsp to javascript file (examples use jQuery): 除此之外,还有两个选项可以将.gsp的值传递给javascript文件(示例使用jQuery):
gsp (here div, span, input, other tags could be used): gsp(此处可以使用div,span,input和其他标签):
<div id="countElem" data-count="${count}">
js(jQuery used here): js(此处使用jQuery):
var count = $("#countElem").data('count');
gsp: GSP:
<g:hiddenField name="countElem" data-count="${count}"/>
js(jQuery used here): js(此处使用jQuery):
// hidden field will have name and id equals to countElem
var count = $("#countElem").val();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.