How to pass arraylist from servlet to javascript?

微笑、不失礼 提交于 2020-12-12 02:07:22

问题


I'm passing an arraylist from servlet by setting it in the attribute and forwarding it to the jsp

Servlet:

ArrayList <String> mylist = new ArrayList <String>();

mylist.add("Superman");

mylist.add("batman");

mylist.add("flash");

request.setAttribute("mylist", mylist);

request.getRequestDispatcher("Welcome.jsp").forward(request, response);
response.sendRedirect("Index.jsp");

Index.jsp

function doPopulateList(obj)
    {

     alert("HELLO"+obj.id +obj.name+obj.value);
     var select = document.getElementsByClassName("my_dropdown1"); 
     alert("all good");
     //var list = new Array();
      var list = '${mylist}'; 
      //var options = ["1", "2", "3", "4", "5"]; 

     alert("All good till arraylist");
     for(var i=0;i<list.length;i++)
         {

         alert(list[i]);

         }

When I'm trying put the arraylist values in the alert box, I'm getting alerts like

[
S
U

I want the alerts to be like

Superman
batman
flash

Pardon me if this is duplicate question.


回答1:


Firstly, you need to traverse the server-side list and add each element to JS array before the servlet does not send the response to the client.

So, this might work:

<script>
   var list = [
      <c:forEach items="${mylist}" var="hero">
        '<c:out value="${hero}" />',  
      </c:forEach>
   ];
   console.log(list);
</script>



回答2:


What's arriving on the client side is not an array but a string. Therefore if you loop you are looping the single characters of the String.

You need to convert the string to a JSON-Object in order to be able to loop the list items.

var list = JSON.parse('${mylist}');


来源:https://stackoverflow.com/questions/44678192/how-to-pass-arraylist-from-servlet-to-javascript

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