我花了最近几个小时在网上寻找答案,但到目前为止没有任何帮助,所以我想我会在这里问自己的问题。
所以长话短说,我想从我的网页调用一个Java类/方法,我已经理解AJAX是最好的方法,通过使用JS,java类和.jsp文件。虽然,到目前为止我只能解析.jsp文件的内容
这是我的html(和JS)文件(index.html)
newfood = food.dup
newfood = food.clone
这是.jsp文件(test.jsp)
<!DOCTYPE html>
<html>
<title>Such wow</title>
<body>
<div id="demo">
<h1>The XMLHttpRequest Object</h1>
<button type="button" onclick="loadDoc()">Change Content</button>
</div>
<script type="text/javascript"
src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.1.1.js"></script>
<script>
function loadDoc() {
console.log("loadDoc is running");
$.ajax({
url : 'test.jsp', // Your Servlet mapping or JSP(not suggested)
type : 'POST',
dataType : 'html', // Returns HTML as plain text; included script tags are evaluated when inserted in the DOM.
success : function(response) {
console.log(response+" = response");
$('#outputDiv').html(response); // create an empty div in your page with some id
},
error : function(request, textStatus, errorThrown) {
alert(errorThrown);
}
});
}
</script>
</body>
</html>
最后,但并非最不重要的是,实际的Java文件(Test.java)
<body>
<%
Test tc = new Test();
out.print(tc.getString());
%>
</body>
正如我所说,这只会在控制台中记录.jsp文件的内容。我想实际调用Test.java的getString方法。我已经在文件系统中编译了Java文件,所以这应该不是问题。
提前感谢您的帮助!