简体   繁体   English

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

[英]How to pass arraylist from servlet to javascript?

I'm passing an arraylist from servlet by setting it in the attribute and forwarding it to the jsp 我通过从servlet传递一个arraylist,方法是在属性中设置它并将其转发到jsp

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

         }

When I'm trying put the arraylist values in the alert box, I'm getting alerts like 当我尝试将arraylist值放在警报框中时,我收到类似

[
S
U

I want the alerts to be like 我希望警报像

Superman
batman
flash

Pardon me if this is duplicate question. 如果这是重复的问题,请原谅我。

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. 首先,您需要遍历服务器端列表,并将每个元素添加到JS数组中,然后servlet才不将响应发送到客户端。

So, this might work: 因此,这可能有效:

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

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. 您需要将字符串转换为JSON-Object才能循环列表项。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM