【问题标题】:How to read Ajax JSON in Java (JEE)?如何在 Java (JEE) 中读取 Ajax JSON?
【发布时间】:2018-05-06 09:27:33
【问题描述】:

我正在尝试读取 java 类中的 ajax json 文件。有人知道如何从那里获取值吗?

function addBook() {
    jQuery.ajex({
        url: "http://localhost:8080/book_service/rest/books/",
        type: "POST",
        contentType: "application/json",  
        dataType:'json',
        data: {
            title:$("#stitle").val(),
            price:$("#sprice").val()
        },
        success: function(data, textStatus, errorThrown) {
            log.out("Added Successfully");
        },
        error : function(jqXHR, textStatus, errorThrown) {
            log.out("Error Adding");
        },
        timeout: 120000,
    });
};

这是我的java类

@POST
public void addBook() {


        String title;
        int price;
        new Books().addBook(title, price);
}

【问题讨论】:

  • 不是jQuery.ajex,而是jQuery.ajaxlog 是什么?
  • 什么意思?我只想从 addBook() 中的数据中获取值

标签: javascript java ajax


【解决方案1】:

我只是找出解决方案...

使用 Application_JSON 注释 @Consumes。使您可以作为通过 JsonObject 传递到方法中的 JSON 对象进行访问。

在 ajax 中,您应该按照以下 JSON 格式传递值,

function addBook() {
    jQuery.ajax({
        url: "http://localhost:8080/book_service/rest/books",
        type: "POST",
        contentType: "application/json",
        data: JSON.stringify( {
            "bid"   :$("#sid").val(),
            "title" :$("#stitle").val(),
            "price" :$("#sprice").val()
        }),
});

@Consumes(MediaType.APPLICATION_JSON)
    public void addBook(JsonObject data) {

        int id = Integer.parseInt(data.getString("bid"));
        String title = data.getString("title");
        double price = Double.parseDouble(data.getString("price"));

        System.out.println(id+" "+title+" "+price);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-19
    • 1970-01-01
    • 2016-12-10
    相关资源
    最近更新 更多