Iterate hashmap stored in Model in javascript

ぐ巨炮叔叔 提交于 2019-12-25 04:13:57

问题


While trying to iterate a map in a javascript function by passing key as below:

        <html> <head> 
    <script type="text/javascript"> 
    function demo(tmp){ 
    <c:forEach var="user" items="${usermap}"> 
    <c:out value="${usermap.get(\"+'tmp'+\").name}"></c:out>    
    </c:forEach>    
    } 
    </script> 
<title>Insert title here</title> </head>
 <body> 
<h1 onclick="demo('user1')">User VO</h1> 
<c:forEach var="user" items="${usermap}"> 
 Key: ${user.key}  - Name: ${user.value.name} - Id: ${user.value.userid}<br/><br/> 
</c:forEach> 
</body> </html>

I am getting blank value. But when I hard code the value of key***user1***, it works.

Servlet Code protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub

    //System.out.println("in servlet doGet:"+ ++count);
    UserVO user1= new UserVO("Y","701");
    UserVO user2= new UserVO("D","834");


    hmap.put("user1", user1);
    hmap.put("user2", user2);
    //hmap.values()
    request.setAttribute("usermap", hmap);
    //response.sendRedirect("User.jsp");
    RequestDispatcher view = request.getRequestDispatcher("User.jsp");
    view.forward(request, response);
    //response.getWriter().append("Served at: ").append(request.getContextPath());
}

Can somebody help me here?


回答1:


The Issue:

You are mixing client side and server side code. JavaScript and JavaServer Pages are executed separately.

  • JSP code is compiled on the server,
  • The result is a HTML, that is delivered to the browser
  • In the browser the JavaScript is executed

So JSP related stuff like:

  • JSTL, JSP Standard Tag Library (tags like <jsp:something> <c:something>)
  • JSP-EL, Expression Language (strings like ${something})

is processed on the server.

You can see, what HTML code is received in browser, by pressing Ctrl+U in Firefox/Chrome.

In your case:

Selecting an option in the select-tag is executed on the client side in browser.
It is too late for EL-evaluation. The EL has bean already evaluated.
You can use ajax to request the needed data (map) according the user selection.

EDIT:

The EL of the hardcoded line is executed on the server and replaced with the value. On the other case, when select-tag is involved, the EL was executed on the server and replaced by var Cfs_id ="";. So the dummy function ignore the parameter serviceId and set the variable always to empty string.

Look the code in your browser. There is only Html and Javascript. The JSP EL are no more there.



来源:https://stackoverflow.com/questions/41381059/iterate-hashmap-stored-in-model-in-javascript

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!