2013-04-04 89 views
0

我是Adobe CQ的新手。我甚至不知道如何提出這個問題如何從JSP Servlet中獲取JSON對象來自Servlet

我必須動態地填充下拉列表,下拉列表應該調用一個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} 

] 

%> 

所以打算用以下的jQuery在我的jsp:

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

但是如何把這個到以上格式的JSP?

回答

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> 
+0

Jouse:我沒有得到它..可以請你詳細說明它... – 2013-04-04 04:16:02

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對象,對象應該從servlet中獲得它。 – 2013-04-04 13:22:05

+0

您可以更改網址和代碼放入點擊事件。 – 2013-04-08 05:49:57