Grails 在 javascript 中的 GSP 站点中使用 grails var
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6995941/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Grails using grails var in GSP Site inside javascript
提问by grailsInvas0r
I have a question using grails variable values in javascript code in a GSP file.
我有一个在 GSP 文件中的 javascript 代码中使用 grails 变量值的问题。
For Example: I have a session value session.getAttribute("selectedValue")and I want to use this value inside javascript code part.
例如:我有一个会话值session.getAttribute("selectedValue")并且我想在 javascript 代码部分中使用这个值。
My solution is now (inside a GSP):
我的解决方案现在是(在 GSP 内):
<%
def js = new String("<script type=\"text/javascript\">")
js += "var jsSelectedValue = " + session.getAttribute("selectedValue") + ";"
js += "</script>"
out << js
%>
and then I have javascript block inside my GSP with jQuery Stuff and so on, there I need this value.
然后我在我的 GSP 中有 javascript 块和 jQuery Stuff 等等,我需要这个值。
Is there another way to have grails variables accessible inside pure javascript code?
是否有另一种方法可以在纯 javascript 代码中访问 grails 变量?
And second question, the exactly other way around. I select for example in a dropdown box and click "save" and then i want to store the value $("#select-box").val() inside a session variable from JS-part.
第二个问题,恰恰相反。例如,我在下拉框中选择并单击“保存”,然后我想将值 $("#select-box").val() 存储在来自 JS-part 的会话变量中。
Thank you very much in advance for your help.
非常感谢您的帮助。
Cheers,
干杯,
Marco
马可
回答by Medrod
Why do not use the javascript GSP-tag? A solution can look like this:
为什么不使用javascript GSP-tag?解决方案可能如下所示:
<g:javascript>
var jsSelectedValue = "${session.selectedValue}";
</g:javascript>
回答by mj.scintilla
The solution to your first problem might be as follows:
您的第一个问题的解决方案可能如下:
UPDATE:Modifications according to @Medrod's solution:
更新:根据@Medrod 的解决方案进行修改:
<script type="text/javascript">
var jsSelectedValue = "${session.selectedValue}";
</script>
And for second question:
Send selected value to server and set session variable.
对于第二个问题:
将选定的值发送到服务器并设置会话变量。