【问题标题】:How to receive json object from servlets with ajax?如何使用 ajax 从 servlet 接收 json 对象?
【发布时间】:2015-06-12 16:15:53
【问题描述】:

doGet 设置项 readState 新值并将其作为 Json 对象发送回 ajax 调用:

PrintWriter out = null;
            try {
                out = resp.getWriter();

                Integer read = Integer.parseInt(req.getParameter("feedReadVal"));

                Gson data = new Gson();
                JsonObject jsonObj = new JsonObject();
                Integer readState = null;
                Item item = new Item();

                readState = 1;
                item.setReadState(readState.byteValue());
                JsonElement element = data.toJsonTree(item);

                jsonObj.add("read", element);
                out.print(jsonObj);
            } catch (Exception e) {
                e.printStackTrace();
                }

调用: System.out.println("JSON OBJECT: " + jsonObj.toString()); 显示类似 JSON OBJECT: {"read":{"readState":1}} 的内容,但是当我尝试在成功函数中获取该数据时抛出错误。我的 jQuery:

var data = "feedReadVal=" + itemRead + "&feedItemId=" + feedItemId
        + "&action=" + 'read';
$.ajax({
    type : "Get",
    url : "FeedItemController",
    data : data,
    dataType : "json",

    success : function(data, textStatus, jqXHR) {
        alert(data.read.readState);
    },
    error : function(jqXHR, textStatus, errorThrown) {
        alert("Something really bad happened ");
    }

}).done(function() {

}); 

我一直收到错误警报。

【问题讨论】:

    标签: java jquery ajax json servlets


    【解决方案1】:

    您需要将其写入流而不是打印

    out.print(jsonObj);改成

    out.write(jsonObj.toString());
    out.flush();
    

    【讨论】:

    • 我找到了解决办法,你需要在写入流后刷新。
    • 哈哈,正要说,很高兴你找到了
    • 如果您添加该信息,我可以接受您的回答
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-15
    • 2017-12-08
    • 2012-03-31
    • 2013-09-07
    • 1970-01-01
    • 2018-06-11
    • 2018-01-30
    相关资源
    最近更新 更多