views:

28

answers:

1

My HTML looks like this:

<script type="text/javascript" src="jquery-1.4.2.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
            $("#btn").click(function(){
                $.post("test.jsp", { "txt": $("#txt").val() },
                function(data){
                    alert(data);
                    $("#res").html(data);
                });
            });
        });

    </script>

It sends the value of the text field "txt" and then my JSP returns List:

<%
String str=request.getParameter("txt");
List ls=new ArrayList();
ls.add(str+"1");
ls.add(str+"2");
ls.add(str+"3");
ls.add(str+"4");
out.print(ls);
%>

My question is how I can get the list elements one by one? Something like data[1].

+1  A: 

You need to return a valid JSON string. You can either use Java JSON libraries or just format the string to be valid JSON (be careful):

out.print('["'+str+'1", "'+str+'2"]');

Then the variable data in your JavaScript callback would be something like: ["txt1", "txt2"]. Then you need to parse it to make it a JavaScript usuable Object (I suggest appending the 'json' dataType to the $.post method, it does the parsing for you).

At this point you can call data[1].

Luca Matteis
Thank you a lot.
Evgeny