我试图用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服从项,所以我需要为每个数组获得它们的属性,所以问题是:我应该如何获得它们的属性?
先谢谢你,希望有人解释我:)
发布于 2015-02-25 22:28:00
在这个站点上也有类似的问题,但一种可能的技术是将本机Java对象而不是JSON传递到页面,并使用EL创建一个for循环来迭代您的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访问这些值,但希望您能得到我想要展示的内容。如果没有,问我更多细节..。
发布于 2015-02-25 23:13:50
最重要的是,您应该使用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());
}
https://stackoverflow.com/questions/28730658
复制相似问题