admin管理员组

文章数量:1430811

I want to create a javascript map from a java map to set a dropdown value depending upon the value selected in another dropdown. Below is the code(not working):

var categoryAndReportsMap = new Object();
<% 
Map<String,Set<String>> categoryAndReportsJ = (Map<String,Set<String>>)      request.getAttribute("categoryAndReports");
for(Map.Entry<String,Set<String>> e : categoryAndReportsJ.entrySet()){ %>
categoryAndReportsMap[ <% e.getKey(); %> ] = <% e.getValue(); %>;
<% } %>

Please suggest how can I achieve this.

I want to create a javascript map from a java map to set a dropdown value depending upon the value selected in another dropdown. Below is the code(not working):

var categoryAndReportsMap = new Object();
<% 
Map<String,Set<String>> categoryAndReportsJ = (Map<String,Set<String>>)      request.getAttribute("categoryAndReports");
for(Map.Entry<String,Set<String>> e : categoryAndReportsJ.entrySet()){ %>
categoryAndReportsMap[ <% e.getKey(); %> ] = <% e.getValue(); %>;
<% } %>

Please suggest how can I achieve this.

Share Improve this question asked May 6, 2013 at 14:21 Pravat PandaPravat Panda 1,0902 gold badges15 silver badges27 bronze badges 4
  • 4 Use a JSON serializer. – SLaks Commented May 6, 2013 at 14:22
  • @dystroy: the : vs = is absolutely not the problem here. The OP just neglected to look at JSP-generated output in webbrowser in order to see the trivial mistake. All those Java variables are namely been printed as JS variable names instead of as JS strings. – BalusC Commented May 6, 2013 at 14:24
  • I voted up SLaks ment, but If you are interested and to give some information to try to understand how it works, as long as I know from javascript, maps doesn't exist. Instead you have associative arrays that works similar. Key => value. Eg. var asocArray = new Array(); asocArray["a"] = "a";... – DaGLiMiOuX Commented May 6, 2013 at 14:26
  • Actually, JavaScript has neither maps nor associative arrays. When you assign string-keyed values to an Array, you're actually creating named properties on the array object itself, the same as if you were doing it on a new Object() instead of a new Array(). This bees important when you try to iterate the values back out; using for...in syntax will net you all of the custom properties as well as "count", etc. – Adrian Commented May 6, 2013 at 14:28
Add a ment  | 

1 Answer 1

Reset to default 3

You need quotes around the keys and values :

categoryAndReportsMap["<%= e.getKey() %>"] = "<%= e.getValue() %>";

But this supposes those strings don't contain quotes themselves. The best solution would be to use a JSON serializer like the excellent gson, this would be as simple as

var categoryAndReportsMap = <%= gson.toJson(categoryAndReportsJ) %>;

本文标签: jspJavascript map from java mapStack Overflow