调用Ajax中的Java方法 [英] Calling a java method in ajax
问题描述
我创造在NetBeans IDE JSP应用程序。我有在调用ajax.Is一个Java类方法的问题,可以这样做
I am creating a jsp application in Netbeans Ide. I am having problems in calling a java class method in ajax.Is it possible to do so
我的java类是这样的:
My java class is something like this:
public class Hello
{
public String execute(String s)
{
return "success";
}
}
我无法弄清楚如何调用使用Ajax execute方法: 我现在的阿贾克斯code是:
I am not able to figure out how to call the execute method using ajax : My current ajax code is:
var val="test string";
$.ajax({
type: "GET",
url: "http://localhost:8084/Shade/src/java/mail/Main.execute",
data: val,
async: true,
cache: false,
success: function (msg) {
alert("hi");
$(".col-1").html(msg);
});
感谢名单提前:)
Thanx in advance :)
推荐答案
AJAX
的缩写异步JavaScript和XML
。它提供了一个与服务器异步通信的能力。
AJAX
is an acronym for Asynchronous JavaScript And XML
. It provides an ability to communicate with the server asynchronously.
要解释,简单来说,你可以发送一个请求到服务器,并继续与用户的用户交互。你不必等待服务器的响应。一旦响应到达,在UI指定区域将自动更新,反映了响应信息。整个页面无需重新加载。
To explain that in simple terms, you can send a request to server and continue user interaction with the user. You need not wait for response from the server. Once the response arrives, a designated area in UI will update itself and reflect the response information. Whole page need not be reloaded.
所以,你不能直接访问Java类网址
来使你的Ajax请求。它不应该任何映射的URL像 JSP
, Servlet的
, PHP
等等。
So, you can not access Java Class directly as url
to make your Ajax request. It should any mapped url like JSP
, Servlets
, PHP
etc.
创建一个JSP(例如的hello.jsp
)
Create a JSP (e.g. hello.jsp
)
<%
String strResponse;
mail.Main objMain = new mail.Main();
strResponse = objMain.execute();
%>
<%=strResponse %>
在Ajax请求
url: "hello.jsp",
编辑:添加例子:
Added Example:
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
function getData() {
var dataToBeSent = {
uName : $("#userName").val() , //
passwd: $("#password").val()
}; // you can change parameter name
$.ajax({
url : 'getDataServlet', // Your Servlet mapping or JSP(not suggested)
data :dataToBeSent,
type : 'POST',
dataType : 'html', // Returns HTML as plain text; included script tags are evaluated when inserted in the DOM.
success : function(response) {
$('#outputDiv').html(response); // create an empty div in your page with some id
},
error : function(request, textStatus, errorThrown) {
alert(errorThrown);
}
});
}
});
在的Servlet / JSP访问您的参数的request.getParameter(UNAME);
In Servlet/JSP access your parameters request.getParameter("uName");
这篇关于调用Ajax中的Java方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!