Skip to content Skip to sidebar Skip to footer

How To Access A Java Object In JavaScript From JSP

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

Solution 1:

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",
  },
}

Solution 2:

Meta of what LeleDumbo said here already:

First, you must understand that JSP is a server-side view technology, whereas JavaScript typically runs on the client (browser).

Now, how you solve the problem in hand. So, you can make an Ajax request from your JavaScript code, which will fetch you the data in JSON/XML format. Then, you can present that data in the browser using JavaScript.

Further reading: jQuery Ajax API and code samnple snippets


Solution 3:

Call the function on the onchange event of select instead of onclick of options. And use:

document.getElementById('GrdDamagedstock_tplRowEdit_ctl00_cmbFromBin').options[ele.options.selectedIndex].innerHTML;

to get the selected value.


Post a Comment for "How To Access A Java Object In JavaScript From JSP"