0

我想从json获取参数,所以我有一个代码:

    @RenderMode(name = "VIEW")
public void serveResource(ResourceRequest resourceRequest, ResourceResponse resourceResponse) throws PortletException, IOException {
            JSONObject jsonObject = JSONFactoryUtil.createJSONObject();

            resourceRequest.setAttribute("resourceUrl", "http://localhost:8080/");

             jsonObject.put("rowsPerPage", 10);
             jsonObject.put("page", 1);
             jsonObject.put("total", 100);

             PrintWriter writer = resourceResponse.getWriter();
             writer.write(jsonObject.toString());
        }

应该用显示以下内容的 JavaScript 方法编写什么:rowsPerPage、page、total

我有一个 JavaScript 代码:

$.getJSON('http://localhost:8080/', function(jd) {
      alert(jd.rowsPerPage);
   });

JSP 页面:

<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>

<portlet:defineObjects />

This is the <portlet:resourceURL var="testURL" id="view.jsp" escapeXml="false" />
<br/><br/>
<div id="myGrid" style="width:600px;height:500px;"></div>
<div id="pager" style="width:600px;height:20px;"></div>

但这是错误的,为什么?

4

1 回答 1

1

检查您的 URLhttp://localhost:8080/是否返回 JSON 响应(您可以直接将 URL 粘贴到浏览器的地址栏中)。这将返回 Liferay 的欢迎页面。

要调用该serveResource方法,您需要resourceURL在 jQuery 函数中传递a,该函数getJSON可以使用 JSP 中的<liferay-portlet:resourceURL>or<portlet:resourceURL>标记生成。

更新:

您应该resourceURL在 javascript 中使用:

<portlet:resourceURL var="testURL" id="view.jsp" escapeXml="false" />

<script>
    $.getJSON('${testURL}', function(data) {
        alert(data.rowsPerPage);
    });
</scrip>

<!-- ${testURL}: This is EL i.e. expression language of JSP. Don't confuse it with jQuery -->
<!-- <%=testURL.toString() %>: You can also use scriptlet instead of using EL. But normally scriptlets as you might know are not recommended -->

另外我想建议通过在方法中包含一些日志语句来确保该serveResource方法实际上是用脚本调用的。

以下是一些关于如何在 Liferay 中使用 Ajax 的示例链接:

  1. 在 Liferay 中使用 Ajax的工作示例。
  2. 博客通过一个简单的示例解释了 ajax 如何在门户中工作的概念。

希望这可以帮助。

于 2012-10-26T10:40:04.613 回答