在ajax中调用java方法 [英] Calling a java method in ajax

查看:55
本文介绍了在ajax中调用java方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 Netbeans Ide 中创建一个 jsp 应用程序.我在 ajax 中调用 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 方法:我当前的ajax代码是:

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

提前谢谢:)

推荐答案

AJAXAsynchronous JavaScript And 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.

因此,您不能以 url 的形式直接访问 Java 类来发出 Ajax 请求.它应该是任何映射的 url,如 JSPServletsPHP 等.

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",

添加示例:

<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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆