最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - call the java method using ajax on button click - Stack Overflow

programmeradmin1浏览0评论

I have a button in blank.jsp (lets say).

<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.

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.

I have a button in blank.jsp (lets say).

<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.

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.

Share Improve this question asked May 20, 2013 at 4:37 SunielSuniel 1,4998 gold badges27 silver badges40 bronze badges 1
  • This has been answered @ stackoverflow./questions/15944000/… – vaisharch Commented May 20, 2013 at 4:45
Add a ment  | 

3 Answers 3

Reset to default 2

try to use this method..

 $.ajax({
            url: '/servlet/yourservlet',
            success: function(result){
            // when successfully return from your java  
            }, error: function(){
               // when got error
            }
        });

I suppose your payment is in a 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");
        }
    });
}
  1. remove the inline onclick from the submit
  2. add an onsubmit handler to the form
  3. cancel the submission

I strongly remend jQuery to do this especially when you have Ajax involved

I assume here the servlet function is in the form tag. If not, exchange this.action with your servlet name

$(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");
    });
  });
});
发布评论

评论列表(0)

  1. 暂无评论