Reputation: 3040
as the title says. I got an object gotten from the Controller, on which one of its attributes is a List. Now i want to pass this List to an external file javascript function.
Something like this:
<a href="#" onClick="showAuthorityOverlay(<c:out value='${userDetail.grantedAuthorityList}'/>)">[SHOW AUTHORITY]</a>
Now the value passed to the javascript is something like this:
[ADMIN_USER, COMMON_USER]
So when i click in that link, i get a javascript error saying:
ADMIN_USER isn't defined.
What's wrong here? is it taking the ADMIN_USER and COMMON_USER as variable names? or what? Kinda weird.
Tried even making an inner script in my jsp to get the list like this:
<script type="text/javascript>
function showAuthorityOverlay() {
var obj = "<c:out value='${userDetail.grantedAuthorityList}'/>";
sendToExternalJSFile(obj);
}
</script>
But still getting the same results. Looks like the values aren't passing correctly through as a List parameter.
Upvotes: 0
Views: 6103
Reputation: 692121
JSTL code is executed at server-side. In this case, instead of being used to generate HTML, it's also being used to generate JavaScript code (which is perfectly valid).
The toString()
method of your list, which <c:out>
calls, returns the toString representation of every Java object in the list, separates them by commas, and surrounds them with brackets. The end result being
[ADMIN_USER, COMMON_USER]
The generate HTML + JavaScript is then downloaded by the browser, which interprets the JavaScript code:
showAuthorityOverlay([ADMIN_USER, COMMON_USER]);
This happens (by accident) to be syntaxically correct JavaScript code. It means: call the function showAuthorityOverlay()
with a JavaScript array as argument. The array contains the value of the two JavaScript variables ADMIN_USER
and COMMON_USER
.
I assume that you in fact want a JavaScript array of strings instead, which should be written as ['ADMIN_USER', 'COMMON_USER']
.
What you should do is transform the Java array into a JSON string in the controller, and then use this JSON string inside the JavaScript code:
showAuthorityOverlay(${jsonString})
Upvotes: 4