JQuery获取Java ArrayList对象

JQuery get Java ArrayList objects

本文关键字:对象 ArrayList Java 获取 JQuery      更新时间:2024-05-29

我正试图用JQuery从jsp中的数组列表中获取对象,并访问它们的参数。例如名称、时间戳等。但是当JQuery中的这些项不算作我需要的对象类型时,我该怎么做呢?这是我的servlet:

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    HttpSession session = request.getSession();
    long id = (Long) session.getAttribute("lastPost");
    ArrayList<Post> listOfPosts = PostRegistry.getInstance().getPostList(id);
    Gson gson = new Gson();
    JsonElement element = gson.toJsonTree(listOfPosts, new TypeToken<List<Post>>() {
    }.getType());
      JsonArray jsonArray = element.getAsJsonArray();
      response.setContentType("application/json");
      response.getWriter().print(jsonArray);
}

这是我的JQuery:

    <script>
    $(document).ready(function() {
        $('#timeline').hide();
        $('#LoadMore').click(function() {
            $.get('LoadMore', function(responseJson) {
                // Parse the json result on somediv
                $.each(responseJson, function(index, item) {
                });
            });
        });
    });
</script>

在这个$.each中,我应该在我收到的数组中迭代,这个数组中充满了Post obejects,所以我需要得到它们每个的属性,所以问题是:我应该如何得到它们的属性?

提前谢谢你,希望有人能解释我:)

在这个网站上也有类似的问题,但一种可能的技术是将本地Java对象而不是JSON传递到页面,并使用EL为创建一个循环来迭代您的arrayList,提取您的值,然后存储在隐藏的输入元素中,这些元素稍后可以由您的JQuery/JavaScripts函数访问,即

<c:forEach var='post' items=${listOfPosts} >
   <c:set var="attribute1" value=${post.attribute1} />
   <c:set var="attribute2" value=${post.attribute2} />
   <input type="hidden" id="postXXXattribute1" value="${attribute1}" />
   <input type="hidden" id="postXXXattribute2" value="${attribute2}" />
</c:forEach>

我省略了一些关于如何将值写入HTML的细节,以便从JQuery或JavaScript轻松访问这些值,但希望您能得到我要向您展示的内容。如果没有,请询问我更多细节。。。

最重要的是,应该使用jQuery.getJSON()而不是常规的jQuery.get()

            $.getJSON('LoadMore', function(data) {
                $.each(data, function(index, item) {
                    var postTitle = item.title; // example: access title property
                });
            });

如果您似乎没有在javascript中迭代Post对象的列表,请使用jQuery.get()进行调试,通过在浏览器中弹出一个消息框来发现实际的JSON结构:

            alert(responseJson);

顺便说一下,使用toJsonTree()没有任何意义;您应该使用toJson()。此外,调用getAsJsonArray()可能会将结果嵌套在一个冗余数组中。此外,通过管道将输出直接发送到响应Writer更有效。像这样:

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    Long id = (Long)request.getSession().getAttribute("lastPost");
    List<Post> listOfPosts = PostRegistry.getInstance().getPostList(id);
    response.setContentType("application/json");
    new Gson().toJson(listOfPosts,
        new TypeToken<List<Post>>(){}.getType(),
        response.getWriter());
}