【问题标题】:Not able to Json response from rest server无法从休息服务器 Json 响应
【发布时间】:2016-04-04 00:51:08
【问题描述】:

我正在尝试使用 JavaScript 解析来自休息服务器的 Json 响应并显示数据。 其余服务器工作正常,只是我无法解析数据。我查看了几十个示例,根据我的理解,代码看起来不错。 这是我第一次尝试学习 Ajax,如果我解决了这个问题,我可以继续我的项目。

这是回复

{"id":"1","author":"Bill Burke","title":"RESTful Java with JAX-RS","year":"2009"}

这是服务器

@Path("/books") // JAX-RS annotation
public class BookResource {

@GET // JAX-RS annotation
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON, MediaType.TEXT_XML })
@Path("/{bookId}")
public Book getBook(@PathParam("bookId") String id) {
    return BookDao.instance.getBook(Integer.parseInt(id));
}
}

这是客户

<!DOCTYPE html>
<html>
<head>
<title>Form to create a new resource</title>

<script type="text/javascript">

function getHTTPObject() {
    var xhr = false;
    if (window.XMLHttpRequest) {
        xhr = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        try {
            xhr = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                xhr = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {
                xhr = false;
            }
        }
    }
    return xhr;
}

function grabFile(file) {
    var request = getHTTPObject();
    if (request) {
        request.onreadystatechange = function() {
            parseJ(request);
        };
        request.open("GET", file, true);
        request.send(null);
    }
}

function parseJ(request) {
    if (request.readyState == 4) {
        if (request.status == 200 || request.status == 304) {

            var obj = JSON.parse(request.responseText);
            document.getElementById("details").innerHTML = obj.id + " " + obj.author + " "
                    + obj.title + " " + obj.year;

        }
    }
}
</script>
</head>
<body>

<a
    href="http://localhost:8080/Distributed_REST_booksServer/rest/books/1"
    onclick="grabFile(this.href); return false;">Book 1</a>
<br>
<div id="details"></div>
</body>
</html>

html console error

html console error after modification

【问题讨论】:

  • 您的服务器返回错误。或者至少是 HTML,因为第一个字符是 &lt;。尝试:try{ var obj = JSON.parse(request.responseText); } catch(e){ console.log(e,' on ',request.responseText); } 进行验证,请并发布结果。
  • 我添加了一个新的截图@henry700
  • 您的服务器返回的是 XML,而不是 JSON!要么正确配置服务器,要么用你的 Javascript 解析 XML。要解析 XML,您需要一个库...您是否尝试过仅在 @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON, MediaType.TEXT_XML }) 上保留 JSON 选项?

标签: javascript json ajax rest


【解决方案1】:

您的服务器正在返回 XML,尝试将其强制为 JSON,并可能在来自客户端的请求中添加一个接受标头。

【讨论】:

  • 我删除了 XML 的 MediaType,只留下了 Json,它可以工作。
猜你喜欢
  • 1970-01-01
  • 2012-12-07
  • 2016-07-23
  • 2011-05-27
  • 1970-01-01
  • 2015-06-28
  • 1970-01-01
  • 2018-05-10
  • 1970-01-01
相关资源
最近更新 更多