【问题标题】:How to obtain Collection<Item> using JQuery and JSON如何使用 JQuery 和 JSON 获取 Collection<Item>
【发布时间】: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


    【解决方案1】:

    我终于找到了问题所在。花了很多时间调试,最后发现这么傻的错误: 而不是指id属性我指的是class属性,所以应该修改:

    <div class="results"></div>
    

    <div id="results"></div>
    

    【讨论】:

      【解决方案2】:

      尝试替换

      for ( var product in products) {
                      $('#results').append(
                              'Name:' + product.name + ' Price: ' + product.price
                                      + '<br>');
                  }
      

      $.each(products, function(index, product) {
          $('#results').append('Name:' + product.name + ' Price: ' + product.price + '<br>');
      });
      

      【讨论】:

      • 我已经尝试过您的解决方案,但结果仍然相同 - 没有输出
      猜你喜欢
      • 1970-01-01
      • 2018-08-17
      • 2017-06-02
      • 1970-01-01
      • 1970-01-01
      • 2020-01-18
      • 1970-01-01
      • 2019-05-10
      • 1970-01-01
      相关资源
      最近更新 更多