passing data from a servlet to javascript code in an Ajax application ?
- by A.S al-shammari
I have a simple jsp/servlet application and I want to add AJAX feature to this app. I use JQuery , but it doesn't matter what javascript framework I use. This is my code:
<script type="text/javascript">
function callbackFunction(data){
$('#content').html(data);
}
$('document').ready(function(){
$('#x').click(function() {
$.post('/ajax_2/servlet',callbackFunction)
});
});
</script>
<body>
<a href="#" id="x">Increase it</a>
<div id="content"></div>
</body>
</html>
Servlet
HttpSession session = request.getSession();
Integer myInteger = (Integer)session.getAttribute("myInteger");
if(myInteger == null)
myInteger = new Integer(0);
else
myInteger = new Integer(myInteger+1);
session.setAttribute("myInteger", myInteger);
response.getWriter().println(myInteger);
The Question:
I use out.print to transfer data from a servlet to javascript code (ajax code) , but If I have a complex structure such as Vector of Object or something like this , what is the best way to transfer the data? what about an XML file , JSON ? Is there any special jsp/servlets library to transfer data from a servlet to ajax application ? How can I parse this data in callbackFunction ?