【问题标题】:How to pass JSON array from Struts 2 action class to jQuery?如何将 JSON 数组从 Struts 2 动作类传递给 jQuery?
【发布时间】:2015-02-04 15:26:30
【问题描述】:

我创建了一个带有操作文件的 Java Web 应用程序,该操作文件将数据从数据库生成到 JSON 数组。现在,我希望将这个 JSON 数组传递给 jQuery?这怎么可能?

仅供参考。我应用了 Struts 2、Spring 和 Hibernate 框架。我没有为这个应用程序使用 PHP。

更新:

这是我的 Struts 2 操作方法:

public static String jsonData = null;

public String generateJson() throws Exception
{
    JSONObject json = null;
    JSONArray jsonArray = new JSONArray();

    this.records = this.recordManager.getAllRecords();

    for (RecordEntity record : records)
    {
        json = new JSONObject();

        json.put("id", record.getId());
        json.put("firstname", record.getFirstName());
        json.put("lastname", record.getLastName());
        json.put("due", record.getDue());
        json.put("email", record.getEmail());
        json.put("website", record.getWebsite());
        jsonArray.put(json);
    }

    System.out.println(jsonArray.toString());

    jsonData = jsonArray.toString(); // jsonData will be passed to jQuery
    return SUCCESS;
}

这是我的 jQuery。我正在使用 BootstrapTable 所以这是结构,我希望将 jsonData 的值传递给这个 jQuery:

$('#record').bootstrapTable({
    method : 'get',
    data: jQuery.parseJSON(VALUE_OF_jsonData_HERE),
    cache : ...
    ...
    ...
});

【问题讨论】:

  • 如果 servlet 在响应输出中打印 JSON 编码的数据,您所要做的就是通过常规 ajax 请求获取它,例如$.getJSON
  • 怎么样?对不起,我没有提到,我是 servlet 和 Struts 2 的新手。
  • 也可以直接将json输出到页面中的javascript变量中。方法在某种程度上取决于它的使用方式
  • 如果您更新问题以包含您目前拥有的 java 代码,您将获得更高质量/更具体的答案。 =]
  • 天啊!问题解决了!谢谢@AndreaLigios!

标签: java javascript jquery json struts2


【解决方案1】:

使用 Ajax 会对您有所帮助,

请参考this 开始,也请先阅读Ajax 以了解背景

【讨论】:

  • 是的,我已经用过了。请注意我已经修改了问题并添加了代码。 :)
猜你喜欢
  • 2013-12-07
  • 1970-01-01
  • 2015-04-03
  • 1970-01-01
  • 2014-12-14
  • 1970-01-01
  • 1970-01-01
  • 2014-02-12
  • 2011-11-13
相关资源
最近更新 更多