简体   繁体   中英

Calling Servlet from JavaScript

I intend to call a function in JavaScript which then calls a Servlet after an <input type="image"> is clicked.

JSP:

<head>
    <script type="text/javascript">
        function callServlet() {
            document.location.href="test-servlet.jsp";
        }
    </script>
</head>

<body>
    <form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post">
    ...
    <input type="image" name="submit"
        src="https://www.paypalobjects.com/webstatic/en_US/btn/btn_buynow_pp_142x27.png"
        onclick="callServlet()" alt="PayPal - The safer, easier way to pay online!">
    </form>
</body>

Servlet ( test-servlet.jsp ):

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("text/html");

    PrintWriter out = response.getWriter();

    out.println("<h1>TestServlet called successfully!</h1>");
}

Context Root: http://localhost:8080/mysite/test-servlet.jsp

However, nothing happens when I click the image button. I am new to JavaScript.

Try this code

<a href="#" onclick="callServlet()"><img
    src="https://www.paypalobjects.com/webstatic/en_US/btn/btn_buynow_pp_142x27.png"
    alt="PayPal - The safer, easier way to pay online!"></a>

EDIT:

Finally we discovered that a servlet should be mapped without extension and doGet method is used to get the request from javascript.

I Could see multiple errors in your jsp .

First of all ,

<form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post">

And also use the img tag with button as Roman says

the url in the action is called , when your form is being submitted

so try replacing it with ,

<form action="./test-servlet" method="post">

and using your JavaScript now,

You cant use window.location.href to make a POST request . check pass post data with window.location.href

<script type="text/javascript">
    function callServlet() {
        document.forms[0].submit;
    }
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM