问题
I'm new to Adobe CQ. I'm not even sure how to put this question
I've to populate a dropdown dynamically,the dropdown should call a JSP which will have JSON response object in scriptlet, Jsp should get the Json object from a servlet.
my jsp should look like below format:
dropdownpopulate.jsp
<%@ page import="com.day.cq.wcm.api.WCMMode,
com.day.cq.wcm.api.components.DropTarget%>
<%
[
{key1,value1},
{key2,value2},
{key2,value3}
]
%>
So planning to use the following jquery in my jsp :
<script>
$(document).ready(function() {
$.get('\ActionServlet',function(responseJson) {
alert('response json:' + responseJson);
});
});
</script>
But how to put this one to JSP in above format?
回答1:
$.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);
});
}
});
hope it's help for you .
回答2:
Your jsp should print the JSON in the response.
JSP file:
<%
//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);
%>
After this, you can access to a string that contains the json object in your ajax callback:
HTML file (or another JSP file):
<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>
来源:https://stackoverflow.com/questions/15801871/how-to-get-json-object-in-jsp-scriptlet-coming-from-servlet