javascript 单击按钮时使用 ajax 调用 java 方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16642682/
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
call the java method using ajax on button click
提问by Suniel
I have a button in blank.jsp (lets say).
我在 blank.jsp 中有一个按钮(可以说)。
<input class="submit_button" type="submit" id="btnPay" name="btnPay" value="Payment"
style="position: absolute; left: 350px; top: 130px;" onclick="javascript:payment();">
when button is clicked I need to call the java method callprocedure() using ajax.
单击按钮时,我需要使用 ajax 调用 java 方法 callprocedure()。
function payment()
{
alert('Payment done successfully...');
........
// ajax method to call java method "callprocedure()"
........
}
I am new to ajax. how can we call the java method using ajax. Please help me soon. Thanks in advance.
我是 ajax 的新手。我们如何使用ajax调用java方法。请尽快帮助我。提前致谢。
采纳答案by mplungjan
- remove the inline onclick from the submit
- add an onsubmit handler to the form
- cancel the submission
- 从提交中删除内联 onclick
- 向表单添加一个提交处理程序
- 取消提交
I strongly recommend jQuery to do this especially when you have Ajax involved
我强烈推荐 jQuery 来做这件事,尤其是当你涉及 Ajax 时
I assume here the servlet function is in the form tag. If not, exchange this.action
with your servlet name
我在这里假设 servlet 函数在表单标签中。如果没有,请this.action
与您的 servlet 名称交换
$(function() {
$("#formID").on("submit",function(e) { // pass the event
e.preventDefault(); // cancel submission
$.post(this.action,$(this).serialize(),function(data) {
$("#resultID").html(data); // show result in something with id="resultID"
// if the servlet does not produce any response, then you can show message
// $("#resultID").html("Payment succeeded");
});
});
});
回答by Raymond
try to use this method..
尝试使用这种方法..
$.ajax({
url: '/servlet/yourservlet',
success: function(result){
// when successfully return from your java
}, error: function(){
// when got error
}
});
回答by me_digvijay
I suppose your payment
is in a servlet
.
我想你payment
在一个servlet
.
All you need is this
你只需要这个
function payment(){
$.ajax({
type: "POST",
url: "yourServletURL",
success: function(data){
alert("Payment successful");
},
error: function (data){
alert("sorry payment failed");
}
});
}