如何将数组列表从servlet传递到javascript?

问题描述:

我正在通过从servlet传递数组列表,方法是在属性中进行设置并将其转发到jsp

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

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]);

         }

当我尝试将arraylist值放在警报框中时,我会收到类似

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

[
S
U

我希望警报像

Superman
batman
flash

如果这是重复的问题,请原谅我.

Pardon me if this is duplicate question.

首先,您需要遍历服务器端列表并将每个元素添加到JS数组中,然后servlet才不将响应发送给客户端.

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.

因此,这可能有效:

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