首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何从Servlet中获取JSP scriptlet中Json对象

如何从Servlet中获取JSP scriptlet中Json对象
EN

Stack Overflow用户
提问于 2013-04-04 11:10:20
回答 2查看 9.1K关注 0票数 0

我是Adobe CQ的新手。我甚至不知道该怎么回答这个问题

我必须动态地填充dropdown,dropdown应该调用一个JSP,它将在scriptlet中有JSON响应对象,Jsp应该从servlet获得Json对象。

我的jsp格式应该如下所示:

dropdownpopulate.jsp

代码语言:javascript
复制
<%@ page import="com.day.cq.wcm.api.WCMMode,
                   com.day.cq.wcm.api.components.DropTarget%>

<%
  [
  {key1,value1},
   {key2,value2},
 {key2,value3}

]

%>

因此,我计划在我的jsp中使用以下jquery:

代码语言:javascript
复制
<script>
$(document).ready(function() {
    $.get('\ActionServlet',function(responseJson) {                          
          alert('response json:' + responseJson);   
    });
});      
</script>

但是如何将其转换为上述格式的JSP呢?

EN

回答 2

Stack Overflow用户

发布于 2013-04-04 12:09:23

您的jsp应该在响应中打印JSON。

JSP文件:

代码语言:javascript
复制
<%
    //obtain the data from a query
    //asuming getClients() return a String in JSON format
    String clients = DB.getClients();

    //this prints de json in the response out
    out.print(clients);
%>

之后,您可以在ajax回调中访问包含json对象的字符串:

HTML文件(或其他JSP文件):

代码语言:javascript
复制
<script type="text/javascript">
    //url from your JSP page
    //data contains the output printed previously
    $ajax(url,function(data){
        //it is convenient to clean de output
        var stringData = data.trim();

        //now that you have a json formated String you need to use a parser that
        //converts the String into a JsonObject
        var jsonData = JSON.parse(stringData);

        //take some actions with the data obtained
        var htmlVar = '';
        for (var i=0; i<jsonData.length; i++){
            //add to htmlVar the HTML code for the options 
            htmlVar += '<option value="'+jsonData[i].clientId+'">'+jsonData[i].clientName+'</option>'
        }
        //load the data into the dropDown element
        $('#clientsDropDown').html(htmlVar)
    });
</script>
票数 0
EN

Stack Overflow用户

发布于 2013-04-04 14:18:19

代码语言:javascript
复制
$.ajax({

        url : "NameServlet",
        dataType : 'json',
        error : function() {

            alert("Error");
        },
        success : function(data) {
            $.each(data.jsonArray, function(index) {
                var selectBox="<select>"
                  $.each(data.jsonArray[index], function(key, value) {
                    selectBox+="<option>"+key + " & value " + value + "</option>";

                 }); 
                 selectBox+="</select>";
                 // given html id which you want to put it 
                 $("#htmlid").html(selectBox);
            });

        }
});

希望对你有帮助。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15801871

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档