从 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
Calling Servlet from JavaScript
提问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 doGet
method 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 img
tag with button
as Roman says
并且还使用img
标签 withbutton
正如 Roman 所说
the url in the action
is 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.href
to make a POST
request . 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>