如何在JSP scriptlet中获取来自Servlet的Json对象

时间:2013-04-04 03:10:20

标签: jquery jsp adobe

我是Adobe CQ的新手。我甚至不确定如何提出这个问题

我要动态填充下拉列表,下拉列表应该调用一个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中?

2 个答案:

答案 0 :(得分: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>

答案 1 :(得分: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);
            });

        }
});
希望对你有帮助。