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

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

call the java method using ajax on button click

javajavascriptajax

提问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

  1. remove the inline onclick from the submit
  2. add an onsubmit handler to the form
  3. cancel the submission
  1. 从提交中删除内联 onclick
  2. 向表单添加一个提交处理程序
  3. 取消提交

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.actionwith 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 paymentis 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");
        }
    });
}