0

I am new to learning Ajax and was wondering if I can call a Java class method directly in $.ajax() call, like example below:

$.ajax({
    url: "com.myPackage.MyClazz#myMethod()",
    ...
})


public class MyClazz {
  public #returnType myMethod() {
     ....//mystuff
  }
}

I have read this and this and plenty of posts and blogs on Ajax on the internet by now, but none of them seems to answer my question directly or indirectly.

It would be great if someone can only provide an example of what should i write in url parameter to call a server side Java method directly.

cFrags
  • 11
  • 5

1 Answers1

0

Simply no you can't but you can send some parameter and filter that parameter to call your method.

$.ajax({
    url : 'YourURLToServlet',
    data : {
        requestType:"getMyMethod",
        pageTimeDuration : $("#durVal").text(),

    },
    type : 'POST',
    dataType : 'text',
    success : function(response) {
        // do here what you want to
    },
    error : function(request, textStatus, errorThrown) {
        console.log(request, textStatus, errorThrown);
    }
});

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {



    String type = request.getParameter("requestType");
    if (type != null) {
        if (type.equals("getMyMethod1")) {
            getMyMethod1(request, response);
        }
        if (type.equals("getMyMethod2")) {
            getMyMethod2(request, response);
        }


    }
}
Ullas Hunka
  • 2,119
  • 1
  • 15
  • 28
  • Thanks @Ullas but can you Please explain whats the request type and pagetimeduration? and what will it do? Also, can you please provide the server side implementation for this? – cFrags Jun 10 '18 at 06:33
  • requesttype and pagetimeduration are the simple custom parameters which you can pass to the servlet. Let's assume if you have two methods in the servlet class foo and foon who captures some input from the client. To call them you can send 1 and 2 in requestType and map it there to call them through switch or if else. – Ullas Hunka Jun 10 '18 at 06:38
  • Yes sure...But one last query...Can you please also clarify why is it not possible to call a Java class method directly? – cFrags Jun 10 '18 at 08:54