简体   繁体   中英

check success and error in ajax

I have a button in jsp like this.

 <input class="submit_button" type="submit" id="btnPay" name="btnPay" value="Payment"  
 style="position: absolute; left: 350px; top: 130px;" onclick="javascript:payment();">

The javascript function calls the java servlet and the servlet calls the function "callprocedure()" when the button is clicked.

 <script>

     function payment()
    {

        var req = $.ajax({
        type: "POST",
        url: '/context/Servlet',
        success: function(result){
         //when successfully return from your java 
        alert('Payment done successfully...');
        }
        }, error: function(){
           // when got error             
           alert("sorry payment failed");            
        }
    });

    }      
</script> 

Now all works fine but my problem is to check the success or error in ajax. How can i check the success or error in ajax in my case.

Thanx in advance ...

You are doing that correctly, However you have syntax error in your code :

function payment() {
    var req = $.ajax({
        type: "POST",
        url: '/context/Servlet',
        success: function (result) {
           // alert data returned by jsp
            alert(result);
            alert('Payment done successfully...');
        },
        error: function (jqXHR,textStatus,errorThrown) {
            // when got error             
            alert("sorry payment failed :" + errorThrown);
        }
    });
}

you can use parameter passed to error callback to know the cause of error

More info

Another way to do it (not very efficient though):

Check the returned value from servlet.

$.post('Servlet',paramName:paramValue,...},function(result) {
  if (result.substring(0,...)=='(expected result)'){ //success

  }else{ //error

  }
});

Hope it helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM