【问题标题】:Jquery Ajax call to java rest api success function is not firingJquery Ajax 调用 java rest api 成功函数没有触发
【发布时间】:2015-07-31 19:36:32
【问题描述】:

我正在尝试将 HTML 表单数据作为 JSON 发送到 java rest api,它会以 JSON 格式生成响应。 这是我的代码。

HTML 表格:

<html>
<body>
<form action ="" method= "post" name= "testform">
    <p> Balance : <input type="text" id="balance" name="balance" /></p>
    <p>Pin : <input type="text" id="pin" name="pin" /></p>
    <p>CardID : <input type="text"  id="cardId" name="cardId" /></p>
    <input type ="submit" id="add-account" value="add user"></input>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="js/main.js"></script>
</body>
</html>

Jquery 代码:

$(function(){
console.log("Jquery called");
$('#add-account').click(function(event){
    event.preventDefault();
    var balance = $("#balance").val();
    var pin = $("#pin").val();
    var cardId = $("#cardId").val();
    var firstcall = 
    $.ajax({
        type: "POST",
        url: "http://localhost:8081/quickpay/webapi/myresource",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify({
            "balance":balance,
            "pin": pin,
            "cardId": cardId
        }), 
        dataType: "json",
        success:function (successResponse,textStatus,jqXHR) {
            alert("first api");         
        },
        error: function (errorResponse1) {
            console.log(errorResponse1);
            alert("failed first api");
        }
    });
});
});

JAVA REST API:

@Path("myresource")
public class MyResource {
    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Account createAccount(Account acc){
        Account account =  AccountService.createAccount(acc.getBalance(),acc.getPin(),acc.getCardId());
        return account;
    }
}

我得到的输出是:

当我尝试在 POSTMAN 中调用 api 时,它运行成功并且数据插入成功。 当我尝试单击 ADD USER 按钮时,数据已成功插入数据库,但 ALERT mesege of success 功能没有出现。

我正在监控谷歌浏览器的网络标签,我发现这个错误在myresource status is cancelled and type is xhr.

将鼠标悬停在 Jquery.min.js 上时,我得到了这个..

n.ajaxTransport.k.cors.a.crossDomain.send@jquery.min.js:4

n.extend.ajax@jquery.min.js:4

(匿名函数)@main.js:9

n.event.dispatch@jquery.min.js:3

n.event.add.r.handle@jquery.min.js:3

问题:如何使 ajax 调用的成功功能起作用?我哪里出错了?

编辑: 我添加了 preventDefault() 方法。所以现在它正在工作!

【问题讨论】:

    标签: javascript java jquery ajax json


    【解决方案1】:

    你没有取消按钮点击所以表单提交

    $('#add-account').click(function(e){
        e.preventDefaul();
        ...
    

    【讨论】:

    • 谢谢兄弟!我之前尝试过使用 preventDefault() 方法,但没有成功。但是现在它正在触发成功功能!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-04
    • 2015-07-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多