passing data from a servlet to javascript code in an Ajax application ?

Posted by A.S al-shammari on Stack Overflow See other posts from Stack Overflow or by A.S al-shammari
Published on 2010-04-06T23:29:35Z Indexed on 2010/04/06 23:33 UTC
Read the original article Hit count: 254

Filed under:
|
|
|

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 ?

© Stack Overflow or respective owner

Related posts about AJAX

Related posts about jQuery