我是javascript和java编程的新手。我有一个带有函数updateInfo()的.java文件。我想在我的.js文件中调用该函数。我怎样才能做到这一点?请帮忙。感谢!!!
答案 0 :(得分:1)
是的,你可以,但不能直接。
一种选择是使用Apache CXF或Jersey等JAX-RS实现。一旦创建了映射到Java文件中的方法的RESTful Web服务,就可以使用JavaScript进行AJAX调用。因此,您当然可以通过REST以RESTful Web服务的形式调用Java方法。
答案 1 :(得分:0)
您不能直接从JavaScript调用java方法。等于java代码是否已编译。
答案 2 :(得分:0)
要使用JavaScript绑定Java代码,您必须先创建Applet。只有在之后,有几种技术可以调用JavaScript from Applet,反之亦然
答案 3 :(得分:0)
首先确保将java编译为jar(并扩展applet / japplet)
您可以使用netscape.javascript.*
示例HTML
<head>
<title>Data Summary Applet Page - Java to JavaScript LiveConnect</title>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252"/>
<script language="javascript">
var userName = "";
// returns number
function getAge() {
return 25;
}
// returns an object
function address() {
this.street = "1 Example Lane";
this.city = "Santa Clara";
this.state = "CA";
}
// returns an array
function getPhoneNums() {
return ["408-555-0100", "408-555-0102"];
}
function writeSummary(summary) {
summaryElem =
document.getElementById("summary");
summaryElem.innerHTML = summary;
}
</script>
<!-- ... -->
</head>
<body>
<script src =
"http://www.java.com/js/deployJava.js"></script>
<script>
<!-- ... -->
deployJava.runApplet(attributes, parameters, '1.6');
</script>
<!-- ... -->
<p id="summary"/> // this HTML element contains
// the summary
<!-- ... -->
</body>
示例java实现:
package javatojs;
import java.applet.Applet;
import netscape.javascript.*; // add plugin.jar to classpath during compilation
public class DataSummaryApplet extends Applet {
public void start() {
try {
JSObject window = JSObject.getWindow(this);
String userName = "John Doe";
// set JavaScript variable
window.setMember("userName", userName);
// invoke JavaScript function
Number age = (Number) window.eval("getAge()");
// get a JavaScript object and retrieve its contents
JSObject address = (JSObject) window.eval("new address();");
String addressStr = (String) address.getMember("street") + ", " +
(String) address.getMember("city") + ", " +
(String) address.getMember("state");
// get an array from JavaScript and retrieve its contents
JSObject phoneNums = (JSObject) window.eval("getPhoneNums()");
String phoneNumStr = (String) phoneNums.getSlot(0) + ", " +
(String) phoneNums.getSlot(1);
// dynamically change HTML in page; write data summary
String summary = userName + " : " + age + " : " +
addressStr + " : " + phoneNumStr;
window.call("writeSummary", new Object[] {summary}) ;
} catch (JSException jse) {
jse.printStackTrace();
}
}
}
More information about invoking javascript from java
More information about invoking java methods from javascript