Call java method in ajax

I am creating a jsp application in Netbeans Ide. I'm having trouble calling a java class method in ajax. Is it possible to do this

My java class looks something like this:

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

I cannot 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 :)

+5
source share
2 answers

AJAXis an abbreviation Asynchronous JavaScript And XML. It provides asynchronous communication with the server.

To explain this in simple terms, you can send a request to the server and continue interacting with the user. You do not need to wait for a response from the server. After the response is received, the designated area in the user interface will update itself and reflect the response information. Unable to reload the entire page.

, Java- url, Ajax. URL-, JSP, Servlets, PHP ..

JSP (, hello.jsp)

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

<%=strResponse %>

Ajax

url: "hello.jsp",

EDIT: :

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

+7

. URL- , . . Java, .

+2

All Articles