[英]Calling Servlet from JavaScript
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
): 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
上下文根:
http://localhost:8080/mysite/test-servlet.jsp
However, nothing happens when I click the image button. 但是,当我单击图像按钮时,什么也没有发生。 I am new to JavaScript.
我是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. 最后,我们发现应该映射一个没有扩展名的servlet,并使用
doGet
方法从javascript获取请求。
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 并像罗马人所说的那样使用带有
button
的img
标签
the url in the action
is called , when your form is being submitted 提交表单时,该
action
的url被称为
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 . 您不能使用
window.location.href
发出POST
请求。 check pass post data with window.location.href 使用window.location.href检查通行证数据
<script type="text/javascript">
function callServlet() {
document.forms[0].submit;
}
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.