1

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?

Cerbrus
  • 70,800
  • 18
  • 132
  • 147
VISH
  • 21
  • 4

2 Answers2

2

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.

daerin
  • 1,347
  • 1
  • 10
  • 17
  • What is prefix="c" about? And what is – VISH Jun 19 '15 at 12:26
  • You can use custom jsp tags from custom taglibs in .jsp. In this example I'm using standard JSTL taglib. See http://www.tutorialspoint.com/jsp/taglib_directive.htm or http://www.tutorialspoint.com/jsp/jsp_standard_tag_library.htm for more info. – daerin Jun 19 '15 at 12:53
0

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?

Community
  • 1
  • 1
kavetiraviteja
  • 2,058
  • 1
  • 15
  • 35