如何从 jQuery 调用 java 函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15654438/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to call a java function from jQuery?
提问by Sarbartha Sengupta
I have a java class 'find' which has a function 'getValues' which returns string array.
我有一个 java 类“find”,它有一个函数“getValues”,它返回字符串数组。
I want to call that function getValue() from a jQuery and convert it into a jQuery array.
我想从 jQuery 调用该函数 getValue() 并将其转换为 jQuery 数组。
Can any one help me how to d so?
任何人都可以帮助我如何做到这一点?
Here is my java code:
这是我的Java代码:
public class search {
int val;
public search(){
val=0;
}
public String getValue(String s){
String ret="";
for(int i=0;i<5;i++)
{
ret += "S"+val+" ";
val++;
}
return ret;
}
}
Here is the jsp:
这是jsp:
<html>
<head>
<%@ page language="java" import="search.*"%>
</head>
<body>
<%
search sh = new search();
%>
<script type="text/javascript">
$(document).ready(function() {
$("#search").keypress(function() {
var queries = <%=sh.getValue()%>; // I am not getting any value here
alert(queries);
});
});
</script>
<form action="">
<table>
<tr>
<td> Search: </td> <td> <input type=text name=search id="search" value=""/></td>
</tr>
</table>
</form>
回答by Aashray
Java code cannot be called inside javascript or jquery. They can be called inside the HTML body using scriplets. Look at this to help you understand better.
无法在 javascript 或 jquery 中调用 Java 代码。可以使用脚本在 HTML 正文中调用它们。看看这个可以帮助你更好地理解。
Calling Java inside JavaScript Function
I would suggest getting the value from the Java class and setting it to a hidden field,like so:
我建议从 Java 类中获取值并将其设置为隐藏字段,如下所示:
<input type="hidden" id="hidden1" value="<%=sh.getValue()%>">
<input type="hidden" id="hidden1" value="<%=sh.getValue()%>">
Then use this field value in your jquery be referring it the id or something.
然后在你的 jquery 中使用这个字段值来引用它的 id 或其他东西。
回答by gshank
Did you try using the scriptlet inside quotes?
您是否尝试在引号内使用 scriptlet?
Like
喜欢
var queries = "<%=sh.getValue()%>";
or
或者
var queries = '<%=sh.getValue()%>';