如何从JSP访问javascript中的java对象? [英] How to access a java object in javascript from JSP?

查看:105
本文介绍了如何从JSP访问javascript中的java对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在JSP中有一个下拉框,列出了java对象(通过MVC控制器addAttribute访问对象)。现在,在从下拉框中选择一个选项时,我想在div中显示所选员工的其他详细信息(例如 - $ {employee.employeeCV},$ {employee.employeeName})。我有一个javascript函数(displayCV())。但不知道该怎么做。

I am having a dropdown box in JSP, listing java object (accessing the object through MVC controller 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 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 -

JAVASCRIPT -

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

}

有人可以帮我吗?

推荐答案

您无法直接从JavaScript访问Java类,您必须在JavaScript(客户端)和Java之间使用某种Web服务通信(服务器),您可以使用onchange事件,它将向服务器发送请求以返回XML / JSON,您可以解析它以获取数据(我看到您正在使用jQuery,它已经有parseJSON方法)并更新了DOM中的相应节点。

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 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, it has parseJSON method already) and update the corresponding node in the DOM.

另一个更容易但不是多用户友好(因为它无法检测更新)是将Java对象转换为JavaScript并更新使用该对象的数据(仍使用onchange)。类似于:

Another easier though 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>
}

现在当JSP解析它时,它会生成,例如:

now when JSP parse this, it would generate, for instance:

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

这篇关于如何从JSP访问javascript中的java对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆