Is it possible to read the value of a dynamic variable like httpRequest.getSession("attr_name") from within a JavaScript?
-
3If you had a server method that can return it to an ajax call, yes. – asawyer Mar 19 '12 at 13:42
-
What server-side language are you using? How is the session being tracked? – Platinum Azure Mar 19 '12 at 13:42
-
1If you mean client side JS: No. If you have some JS environment on your server machine you can feed those parameters into it. I assume your server language is Java? – Sirko Mar 19 '12 at 13:43
-
No I mean client side. I would like to dynamically get attribute values from my HTTP Session object on the client side but from a javascript. My server language is Java. – fmjaguar3 Mar 19 '12 at 13:55
2 Answers
(With Javascript, I assume that you mean client script in the browser.)
No, that is not possible. The contents of the Session object never leaves the server, so client script can't read Session data directly.
If you want to access it in the browser, you have to read the data out of the Session object and send it along in the response (for example in a hidden field), or provide a web service that reads data from the Session object and returns to the browser.

- 687,336
- 108
- 737
- 1,005
As I said in my comment, the only way would be some kind of Ajax call and request it from the server. I dont know what backend your using, here's how I would do it in Asp.net MVC and jQuery.
(If there are minor syntax errors, I apologize - not in front of a compiler)
public class HomeController : Controller
{
//abstract the session code away, don't let the evil javascript touch
//it directly. Ideally this would all be in a seperate logic class or something.
public string NameAttribute
{
get
{
return Session["attr_name"] as string ?? string.empty;
}
}
[HttpGet]
public string GetNameAttribute()
{
return NameAttribute;
}
public ActionResult Index()
{
return View();
}
}
<script>
$(function(){
$.get( 'home/GetNameAttribute', function( response ) {
var name = response; //don't forget error checking, ommited
});
});
</script>
Alternatively, you could always write down the values you need into hidden fields, and read them with normal javascript.

- 17,642
- 8
- 59
- 87