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

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

问题描述

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

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');
}

我该怎么做?

推荐答案

您不能直接从 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 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.

不过,另一种更简单的方法是转换"将 Java 对象转换为 JavaScript 并使用该对象更新数据(仍然使用 onchange).类似的东西:

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

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

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

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

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

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