Question

I'm trying to access a session variable from jquery dynamically .

This is working console.log("${session.application?.sideNavOptions[0]}");

But I need to do something like this.

var application = $("#app").html(); console.log("${session."+application+"?.sideNavOptions[0]}");

Is it possible?

Thanks in advance

Was it helpful?

Solution

You are trying to mix server and client here in a manner which isn't going to work (As stated in my comments). Here is an alternative.

Create a simple controller that you can pass ajax requests to for specific session variables. The controller might look something like this

package com.example

import grails.converters.JSON

class MySimpleController {
  def gimmieValue() {
     String value = session["${param.key}"] as String
     render [result: value] as JSON
  }
}

This controller basically takes one parameter called 'key' and will return whatever is stored in the session with that key. The resulting JSON object has the value under the property 'result'.

The client side code to use this controller might look like this:

$.ajax({
  dataType: "json",
  url: "${createLink(controller: 'mySimple', action: 'gimmieValue')}",
  data: { key: "the-key-from-the-session-you-want" },
  success: function(data) {
    console.log("The server says that the value is: " + data.result);
  }
}

This is a very simplistic example and you should understand that you are essentially opening up your entire session storage through this controller. Which poses a security threat. I would recommend you lock down what keys can and can not be returned in your controller instead of just allowing any key (as I have shown).

This assumes you are using jQuery on the client-side as well. Hope this helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top