如何从Sling到Jquery读取数据?

时间:2017-02-13 12:16:16

标签: jquery aem sling

作为AEM UI开发的一部分,我编写了一个Sling Servlet和Jquery。我需要触发Servlet使用Jquery和从Servlet读取数据到Jquery?任何帮助?

我的Jquery:

window.location.href = Granite.HTTP.externalize("/bin/dam/TimelineVersion"); 

var val=""; // Here I need to Read String Data from Servlet
alert(val);

My Sling Servlet:

@SlingServlet(paths="/bin/dam/TimelineVersion", methods = "GET", metatype=true)
@Properties({
        @Property(name = "service.pid", value = "com.hpe.dam.author.support.servlet.TimelineVersion", propertyPrivate = false),
        @Property(name = "service.vendor", value = "HPE", propertyPrivate = false) })
public class TimelineVersion extends SlingSafeMethodsServlet{

    @Reference
    private SlingRepository repository;

    public void bindRepository(SlingRepository repository) {
        this.repository = repository; 
    }

    @Override
    protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException {

        try {
            String Data="This value i have to get in Jquery";
        } catch (Exception e) {
        }
    }
}

1 个答案:

答案 0 :(得分:1)

您需要重构您的servlet以实际写出响应(我建议您将JSON发送到浏览器):

@SlingServlet(paths="/bin/dam/TimelineVersion", methods = "GET", metatype=true)
@Properties({
        @Property(name = "service.pid", value = "com.hpe.dam.author.support.servlet.TimelineVersion", propertyPrivate = false),
        @Property(name = "service.vendor", value = "HPE", propertyPrivate = false) })
public class TimelineVersionServlet extends SlingSafeMethodsServlet {

    @Reference
    private SlingRepository repository;

    private static Logger log = LoggerFactory.getLogger(TimelineVersionServlet.class);

    @Override
    protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException {
        try {
            String data = "This value i have to get in Jquery";
            response.getWriter().write(data);
        } catch (Exception e) {
             log.error(e); // handle appropriately
        }
    }
}

以下是您的Javascript:

$.get('/bin/dam/TimelineVersion')
    .success(function(data) {
        console.log(data);
    })
    .error(function() {
        console.log('[ERROR] Could not perform request');
    });

这是一个使用jQuery调用的Sling Servlet的工作示例:https://github.com/mickleroy/aem-ajax-search