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

查看:38
本文介绍了如何从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天全站免登陆