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

问题描述 投票:0回答:2

我是 Adobe CQ 的新手。我什至不知道如何提出这个问题

我必须动态填充下拉列表,下拉列表应该调用 JSP,该 JSP 将在 scriptlet 中包含 JSON 响应对象,Jsp 应该从 servlet 获取 Json 对象。

我的 jsp 应该如下所示:

dropdownpopulate.jsp

<%@ page import="com.day.cq.wcm.api.WCMMode,
                   com.day.cq.wcm.api.components.DropTarget%>

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

]

%>

所以计划在我的jsp中使用以下jquery:

<script>
$(document).ready(function() {
    $.get('\ActionServlet',function(responseJson) {                          
          alert('response json:' + responseJson);   
    });
});      
</script>

但是如何将这个以上述格式放入 JSP 中呢?

jquery jsp adobe
2个回答
0
投票
$.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
投票

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

JSP文件:

<%
    //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 文件):

<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>
© www.soinside.com 2019 - 2024. All rights reserved.