gpt4 book ai didi

java - 如何使用 JQuery 和 Bootstrap 布局 json 对象数组

转载 作者:太空宇宙 更新时间:2023-11-04 06:07:26 24 4
gpt4 key购买 nike

我正在使用 struts 2、mysql、jquery、jsp、bootstrap、gson 和 tomcat 开发在线购物应用程序。

我有名为 Product 的 Java 实体、返回 json 产品数组的 Controller 操作和通过 ajax 调用该操作并向用户显示所有产品的 jsp 页面。

我不明白的是如何显示这样的json数组。

我在谷歌上搜索了JQuery Datatables plugin因为它建议过滤和分页,但我不知道应该如何配置它,因为我想不按产品字段对信息进行分组,而是按每个产品实体进行分组,如下图所示: example of products view

如果有更好的插件或其他解决方案,请提出建议,但请注意,在将来的开发中我想添加Product的图像。

产品实体:

public class Product{
private long id;
private String name;
private double price;
private long storeId;
//getters and setters
}

和 Action Controller 类ViewAllProducts:

public class ViewAllProducts extends ActionSupport {
@Override
public String execute() throws Exception {
LOG.trace("Start execute");
Collection<Product> products = productDAO.findAll();
Gson gson = new Gson();
JsonElement element = gson.toJsonTree(products,
new TypeToken<Collection<Product>>() {
}.getType());
JsonArray jsonArray = element.getAsJsonArray();
HttpServletResponse response = ServletActionContext.getResponse();
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().print(jsonArray);
LOG.trace("Finished execute");
return null;
}
}

这是我的 jsp 页面代码,我在其中执行 Ajax 调用来执行此操作:

<%@ include file="/WEB-INF/jspf/directive/page.jspf"%>
<%@ include file="/WEB-INF/jspf/directive/taglib.jspf"%>
<html>
<%@ include file="/WEB-INF/jspf/head.jspf"%>
<body>
<%@ include file="/WEB-INF/jspf/menu.jspf"%>
<div class="container" style="width: 40%">
<div id="results"></div>
</div>
<script type="text/javascript">
$.ajax({
type : 'GET',
dataType : 'json',
url : 'product/upload_products',
success : function(products) {
$.each(products, function(index, product) {
$('#results').append(?????);
});
}
},
})
</script>
</body>
</html>

Json 数组输出示例:

    [{"name":"Amet Ultricies Incorporated","price":679.71,"storeId":1,"id":1},
{"name":"Ut Nisi A PC","price":1133.43,"storeId":1,"id":2},
{"name":"Ligula Limited","price":156.66,"storeId":1,"id":100}]

最佳答案

使用 .each 循环遍历所有内容并将值写入页面。如果每个项目 ID 用作 div ID 或类,您可以使用它来定位每个产品。但在没有看到实际标记的情况下,很难说每个值将如何使用。您需要在成功函数中执行类似的操作。

success: function (data) {
$(data.products).each(function (index, item) {

$("#"+item.id+" .name").html(item.name);
$("#"+item.id+" .price").html(item.price);
$("#"+item.id+" .store").html(item.store);

});
},
error: function () {}

});.

当然,只有当页面上已有数据时,这才有效。如果您需要在页面上构建完整的产品列表,我建议您使用 JS 模板系统,例如 Mustache JS 和 ICanHaz。 http://icanhazjs.com/

关于java - 如何使用 JQuery 和 Bootstrap 布局 json 对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29130136/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com