从 JavaScript 调用 Servlet

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26713270/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 06:21:59  来源:igfitidea点击:

Calling Servlet from JavaScript

javajavascriptjspservlets

提问by silver

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

我打算在 JavaScript 中调用一个函数,然后在<input type="image">单击后调用一个 Servlet 。

JSP:

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

小服务程序 ( 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.

上下文根:http://localhost:8080/mysite/test-servlet.jsp

但是,当我单击图像按钮时,没有任何反应。我是 JavaScript 的新手。

采纳答案by Roman C

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 doGetmethod is used to get the request from javascript.

最后我们发现 servlet 应该被映射而没有扩展名,并且doGet方法用于从 javascript 获取请求。

回答by Santhosh

I Could see multiple errors in your jsp .

我可以在您的 jsp 中看到多个错误。

First of all ,

首先 ,

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

And also use the imgtag with buttonas Roman says

并且还使用img标签 withbutton正如 Roman 所说

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

中的 urlaction被调用,当您的表单被提交时

so try replacing it with ,

所以尝试将其替换为,

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

and using your JavaScript now,

现在使用你的 JavaScript,

You cant use window.location.hrefto make a POSTrequest . check pass post data with window.location.href

你不能window.location.href用来提出POST请求。使用 window.location.href检查传递发布数据

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