Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access a Java object in JavaScript from JSP [duplicate]

I have a dropdown box in JSP, listing a Java object (accessing the object through the MVC controller's addAttribute). Now, on selection of an option from the dropdown box, I would like to display the selected employee's other details (example - ${employee.employeeCV}, ${employee.employeeName}) in a div. I have a JavaScript function for that (displayCV()). But I am not sure how to do this.

JSP -

<c:forEach items="${employees}" var="employee">
  <option value="${employee.id}" onclick="displayCV();">
    ${employee.employeeName}
  </option>
</c:forEach>

<b>CV:</b>

JavaScript

function displayCV() {
    var valueSelected = $('#employeeList').val();
    var div = $('#candidateDiv');
}

How can I do this?

like image 966
sara Avatar asked Jul 05 '11 01:07

sara


1 Answers

You can't access Java classes directly from JavaScript. You have to use some kind of web service communication between the JavaScript (client) and Java (server). You can make use of the onchange event which will send a request to the server to return XML/JSON which you can parse to get the data (I see you're using jQuery, and it has parseJSON method already) and update the corresponding node in the DOM.

Another easier way, though, that is not multi-user friendly (because it can't detect updates) is to "convert" the Java object to JavaScript and update the data using that object (still using onchange). Something like:

// This is JavaScript code written in the JSP
var employees = {
  <c:forEach items="${employees}" var="employee">
  "${employee.id}": {
    name:"${employee.employeeName}",
    cv:"${employee.employeeCV}",
  },
  </c:forEach>
}

Now when JSP parses this, it would generate, for instance:

var employees = {
  "1": {
    name:"foo",
    cv:"cv1",
  },
  "2": {
    name:"bar",
    cv:"cv2",
  },
}
like image 65
LeleDumbo Avatar answered Oct 23 '22 15:10

LeleDumbo