Calling a java method in ajax

后端 未结 2 1881
醉酒成梦
醉酒成梦 2020-12-05 06:00

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

My java class is something like

相关标签:
2条回答
  • 2020-12-05 06:29

    You cannot call the method directly. You should map an URL to the method you want to call. This can be done in a servlet. If you're already serving pages through your Java code, you just add a new method to serve a page with the content you want.

    0 讨论(0)
  • 2020-12-05 06:47

    AJAX is an acronym for Asynchronous JavaScript And XML. It provides an ability to communicate with the server asynchronously.

    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.

    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.

    Create a JSP (e.g. hello.jsp)

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

    In Ajax request

    url: "hello.jsp",
    

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

    In Servlet/JSP access your parameters request.getParameter("uName");

    0 讨论(0)
提交回复
热议问题