Snowy Coder Girl
Snowy Coder Girl

Reputation: 5518

Get Request Attributes in JavaScript

When loading a page, I have the following in my controller:

request.setAttribute("myAtt", "Testing");

I want to access this in my JSP file. In the HTML section, I am familiar with using things like:

${myAtt} ${requestScope.myAtt}

and the like. However, I've never been sure how to access request parameters in JavaScript. I've tried a number of things, such as:

var jsAtt = ${myAtt};
var jsAtt = '${myAtt}';
var jsAtt = eval(${myAtt});
var jsAtt = eval('${myAtt}');

etc, but nothing seems to work.

Is there a way to grab request attributes via JavaScript? Please no jQuery, servlets, etc. I want pure JavaScript code.

I am kind of amazed I didn't find this already asked. So sorry if it is a duplicate and I just didn't see the orignal.

Upvotes: 9

Views: 67263

Answers (4)

Laurent
Laurent

Reputation: 519

Put the following code inside the head tag of your jsp page (not in a js file) :

<script type="text/javascript">
var jsAtt = '<%= request.getAttribute("myAtt") %>';
</script>

But your string must NOT contains the simple quote because it will break the interpretation of the String in the jsp.

If you need String with simple quote, you will need, for example, to replace them on the server side by "&#39;" :

request.setAttribute("myAtt", myAtt.replaceAll("'", "&#39;"));

And replace it again in your JSP :

<script type="text/javascript">
var jsAtt = '<%= request.getAttribute("myAtt") %>';
jsAtt = jsAtt.replace(/&#39;/g, "'");
</script>

For Object instead of String, you can use JSON to pass them as a String.

Upvotes: 0

Snowy Coder Girl
Snowy Coder Girl

Reputation: 5518

Using the following should work.

var jsAtt = '${myAtt}';

I think I stumbled across issues because of trying to dynamically generate the string based off my needs, which JavaScript seems to not like. For example, this would have issues:

var counter = 1;
var jsAtt = '${myAtt' + counter + '}';

JavaScript seems to recognize the request parameter syntax, but only if it's completely predetermined.

Upvotes: 17

pacman
pacman

Reputation: 1061

I have not tested this but have you tried this?

${pageContext.request.myAtt}

Upvotes: -1

Mechkov
Mechkov

Reputation: 4324

For GET requests you can get the values from the QueryString. Check this page: http://www.thimbleopensource.com/tutorials-snippets/get-request-parameters-using-javascript

I am not sure about POST requests though.

Upvotes: 0

Related Questions