【发布时间】:2015-05-16 23:20:49
【问题描述】:
我正在使用 tomcat、jsp、bootstrap、struts2、mysql、gson 开发 java web 项目。
我有产品实体:
public class Product{
private long id;
private String name;
private double price;
private long storeId;
//getters and setters
}
和动作控制器类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 class="results"></div>
</div>
<script type="text/javascript">
$.ajax({
type : 'GET',
dataType : 'json',
url : 'product/upload_products',
success : function(products) {
for ( var product in products) {
$('#results').append(
'Name:' + product.name + ' Price: ' + product.price
+ '<br>');
}
},
})
</script>
</body>
</html>
当我在 Mozilla 中调试时,我看到对 ViewAllProducts 的调用成功并且返回了一些 json:
但我在页面上看不到它,所以我在success 属性中的功能不起作用。应该如何解决?
【问题讨论】:
标签: java jquery ajax json gson