最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

variables - Grails using grails var in GSP Site inside javascript - Stack Overflow

programmeradmin5浏览0评论

I have a question using grails variable values in javascript code in a GSP file.

For Example: I have a session value session.getAttribute("selectedValue") and I want to use this value inside javascript code part.

My solution is now (inside a 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.

Is there another way to have grails variables accessible inside pure javascript code?

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.

Thank you very much in advance for your help.

Cheers,

Marco

I have a question using grails variable values in javascript code in a GSP file.

For Example: I have a session value session.getAttribute("selectedValue") and I want to use this value inside javascript code part.

My solution is now (inside a 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.

Is there another way to have grails variables accessible inside pure javascript code?

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.

Thank you very much in advance for your help.

Cheers,

Marco

Share Improve this question asked Aug 9, 2011 at 12:08 grailsInvas0rgrailsInvas0r 6552 gold badges10 silver badges25 bronze badges 1
  • You're not really referencing any grails variables in the code above. What you're actually doing is using generating javascript code from a template. This template can access the session because it is processed on the server side. – Dónal Commented Aug 9, 2011 at 14:45
Add a ment  | 

2 Answers 2

Reset to default 12

Why do not use the javascript GSP-tag? A solution can look like this:

<g:javascript>
    var jsSelectedValue = "${session.selectedValue}"; 
</g:javascript>

The solution to your first problem might be as follows:

UPDATE: Modifications according to @Medrod's solution:

<script type="text/javascript">
var jsSelectedValue = "${session.selectedValue}";
</script>

And for second question:
Send selected value to server and set session variable.

发布评论

评论列表(0)

  1. 暂无评论