问题
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