How to copy java Array into javascript Array?

1.2k views Asked by At

I have a .jsp page in which I used on click JavaScript function for further validation and other processing stuff. Now I've created an array in jsp scriptlets and how do I pass into this JavaScript function that gets called when submit button is hit? I tried something like this:

var jsArray = <%=lineArray%>;

But that didn't work out.
In fact the function wasn't getting called after I the put above scriptlet. So how do I copy this java array into a JavaScript array?

2

There are 2 answers

2
daerin On

Try something like this:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

var jsArray = [ 
  <c:forEach var="item" items="${lineArray}">
   <c:out value="${item}"/>,
  </c:forEach>
];

This will generate javascript array variable jsArray and put the Java lineArray values into it. If that's what you need to do.

0
kavetiraviteja On

Actually You can't Access Java object(server) directly Into "JavaScript"(client). You have to Create a service(Ajax call) and get the response Object from the server........

But you can do something like this.....

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

 var jsArray = {
      <c:forEach items="${employees}" var="employee">
      "${employee.id}": {
        name:"${employee.employeeName}",
        cv:"${employee.employeeCV}",
      },
      </c:forEach>
    }

After Jsp parse....

var employees = {
  "1": {
    name:"foo",
    cv:"cv1",
  },
  "2": {
    name:"bar",
    cv:"cv2",
  },
}

Then you can modify js object as per your need...

Check Below link For further clarification....

How to access a java object in javascript from JSP?