6

我正在 Netbeans Ide 中创建一个 jsp 应用程序。我在 ajax 中调用 java 类方法时遇到问题。是否可以这样做

我的java类是这样的:

public class Hello
{
    public String execute(String s)
    {
        return "success";
    }
}

我无法弄清楚如何使用 ajax 调用执行方法:我当前的 ajax 代码是:

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);
});

提前谢谢:)

4

2 回答 2

9

AJAX是 的首字母缩写词Asynchronous JavaScript And XML。它提供了与服务器异步通信的能力。

简单来说,您可以向服务器发送请求并继续与用户进行用户交互。您无需等待服务器的响应。一旦响应到达,UI 中的指定区域将自行更新并反映响应信息。整个页面不需要重新加载。

因此,您不能直接访问 Java 类url来发出您的 Ajax 请求。它应该是任何映射的 url,如,JSP等。ServletsPHP

创建一个 JSP(例如hello.jsp

<%
String strResponse;
mail.Main objMain = new mail.Main();
strResponse = objMain.execute();
%>

<%=strResponse %>

在 Ajax 请求中

url: "hello.jsp",

编辑:添加示例:

<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");

于 2013-04-11T09:10:29.000 回答
3

您不能直接调用该方法。您应该将 URL 映射到要调用的方法。这可以在 servlet 中完成。如果您已经通过 Java 代码提供页面,则只需添加一个新方法来提供包含所需内容的页面。

于 2013-04-11T08:28:36.137 回答